How To Add Commas To A Number In Swift

For prices or other purposes, sometimes you’ll need to format in a pretty fashion.

How To Add Commas To A Number In Swift

Use NSNumberFormatter.

let bigNumber = 1234567890
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
guard let formattedNumber = numberFormatter.string(from: NSNumber(value: bigNumber)) else { return }
print(formattedNumber)

This prints 1,234,567,890

How To Add Dollar Signs

Set the numberStyle to .currency:

let bigNumber = 1234567890
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .currency
guard let formattedNumber = numberFormatter.string(from: NSNumber(value: bigNumber)) else { return }
print(formattedNumber)

This prints $1,234,567,890.00

How To Convert Numbers To Words

Set the numberStyle to .spellOut:

let bigNumber = 1234567890
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .spellOut
guard let formattedNumber = numberFormatter.string(from: NSNumber(value: bigNumber)) else { return }
print(formattedNumber)

This prints one billion two hundred thirty-four million five hundred sixty-seven thousand eight hundred ninety

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts