Keoros Keoros - 9 months ago 45
Swift Question

Format a number to string with thousand separators and always has 2 digits after decimal point in swift

How to format


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