How to format 5432.1
to 5,432.10
.
We can use string formatting to force it always show 2 digtis.
let n = 5432.1
let s = String(format: "%.2f", n) //5432.10
We can use number formatter to add thousand separators.
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
let s2 = formatter.stringFromNumber(n) //5,432.1
But how can we combine both? Are there any way to convert that directly? Or do I have to manipulate those two string results to get the final result?
See NSNumberFormatter.minimumFractionDigits
.
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.minimumFractionDigits = 2
let s2 = formatter.stringFromNumber(n) //5,432.10
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