swiftprintlnnsformatter

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 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?


Solution

  • 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