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
?
When you display a number in Swift (Float, Double, Int) it will display without grouping separators. By default a number like 4,592,028.0 will display like: 4592028.0 You need to use the NumberFormatter (NSNumberFormatter) class to convert your number into a pretty String for a text field.
The Swift 1's println function was replaced with the “print” function. In Swift 1, println would print a line of text, with a “newline” character at the end, so each call to println would be on a new line.
The "%f" format string means "a floating point number," but "%. 2f" means "a floating-point number with two digits after the decimal point. When you use this initializer, Swift will automatically round the final digit as needed based on the following number.
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
Everything about the format of a number as a string can be adjusted using a NSNumberFormatter:
let nf = NSNumberFormatter() nf.numberStyle = NSNumberFormatterStyle.DecimalStyle nf.maximumFractionDigits = 2 println(nf.stringFromNumber(0.33333)) // prints 0.33
You can escape quotes with a backslash
println("\"God is dead\" -Nietzsche")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With