It is recommended to round the decimals but i am facing an scenario where i just need to cut down the precision.
Output: 15.96 to 16.0
Codes:
var value: AnyObject = dict.valueForKey("XXX")!
var stringVal = NSString(format:"%.1f", value.floatValue)
I thought this will be simple but found tricky. Your thoughts on this is highly appreciated.
You might get a decent solution by using String(format: "%. 2f", weight >= 0 ? weight - 0.005 : weight + 0.005) but the real solution is to use NumberFormatter and choosing the rounding mode correctly (probably . down ).
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.
Rounding Numbers in SwiftBy using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.
Use a NSNumberFormatter
and configure its rounding mode accordingly:
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 1
formatter.roundingMode = .RoundDown
let s = formatter.stringFromNumber(15.96)
// Result: s = "15.9"
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