Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 963
Keoros Avatar asked Oct 18 '25 19:10

Keoros


1 Answers

See NSNumberFormatter.minimumFractionDigits.

let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.minimumFractionDigits = 2
let s2 = formatter.stringFromNumber(n)  //5,432.10
like image 131
Alexander Avatar answered Oct 20 '25 08:10

Alexander