For prices or other purposes, sometimes you’ll need to format in a pretty fashion.
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
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
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
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.