How To Add Commas To A Number In Swift

By Eddy Chung

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, you'll love my free guide: Secrets To iOS Development. Speed up your learning curve - hundreds of students have already downloaded. Thanks for reading!
Profile Picture of Eddy Chung

Eddy Chung

I am a professional iOS developer in Silicon Valley. I teach iOS development on ZeroToAppStore.com. If you'd like to learn more about me click here or you can contact me at: eddy@zerotoappstore.com

Similar Posts