How would I add commas to a number that I'm retrieving from a JSON in swift.
Example 31908551587 to 31,908,551,587
I'm so confused and I have no idea what to do.
extension Int { func withCommas() -> String { let numberFormatter = NumberFormatter() numberFormatter. numberStyle = . decimal return numberFormatter. string(from: NSNumber(value:self))! } }
You can do it with NSNumberFormatter
Swift 4
let largeNumber = 31908551587 let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal let formattedNumber = numberFormatter.string(from: NSNumber(value:largeNumber))
Swift 3
let largeNumber = 31908551587 let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal let formattedNumber = numberFormatter.string(from: NSNumber(value:largeNumber))
Swift 2
let largeNumber = 31908551587 let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle let formattedNumber = numberFormatter.stringFromNumber(largeNumber)
Expanding on Özgür Ersil's answer, you can isolate the functionality with an extesion to Int:
extension Int { func withCommas() -> String { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal return numberFormatter.string(from: NSNumber(value:self))! } }
To then use on your code as:
largeNumber.withCommas()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With