How to use println in Swift to format number

sirab333 picture sirab333 · Jun 8, 2014 · Viewed 51.4k times · Source

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 println in Swift?

Here's a regular Swift println statement:

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

So how do you limit decimal places?

Also, how do you escape double-quotes in println?

Answer

sirab333 picture sirab333 · Jun 8, 2014

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