Swift how to format a large number with thousands separators?

Swift Xcode 6.3, SOLVED (I decided to leave the $ in the code). If you don't want a $ in the output, change .CurrencyStyle to .DecimalStyle

var fv = 3534234.55 
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
formatter.maximumFractionDigits = 0;
resultFV.text = formatter.stringFromNumber(fv) // result: $3,534,235 –

Update for Swift 4.1 currency string:

let balance = 1234567

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.maximumFractionDigits = 0

let result = formatter.string(from: NSNumber(value: balance)) 
// result: $1,234,567

You can change formatter.numberStyle to .decimal to leave it as number without "$" sign.


You should use a NumberFormatter for that:

let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal

resultFV.text = numberFormatter.string(from: fv)

In Swift 3,

NumberFormatter.localizedString(from: NSNumber(value: whatever), number: NumberFormatter.Style.decimal)

Tags:

Swift