sirab333 sirab333 - 2 years ago 103
Swift Question

How to use println in Swift to format number

When logging-out a float in Objective-C you can do the following to limit your output to only 2 decimal places:

float avgTemp = 66.844322156
NSLog (@"average temp. = %.2f", avgTemp);

But how do you do this in Swift?
And how do you escape other characters in
in Swift?

Here's a regular Swift

println ("Avg. temp = \(avgTemp)")

So how do you limit decimal places?

Also, how do you escape double-quotes in

Answer Source

Here's the shortest solution I found thus far:

let avgTemp = 66.844322156
println(NSString(format:"%.2f", avgTemp))

Its like the swift version of NSString's stringWithFormat

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download