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
?
Here's the shortest solution I found thus far:
Its like the swift version of NSString's
stringWithFormat
Everything about the format of a number as a string can be adjusted using a NSNumberFormatter:
You can escape quotes with a backslash
If you need to print floating point numbers often with a certain precision, you could extend Float and Double with convenience methods. For example, for 2 significant figure precision:
Then when you need to print things: