Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add commas to a number in swift?

Tags:

xcode

swift

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.

like image 411
Omar Qureshi Avatar asked Jun 24 '15 08:06

Omar Qureshi


People also ask

How to add comma in numbers in Swift?

extension Int { func withCommas() -> String { let numberFormatter = NumberFormatter() numberFormatter. numberStyle = . decimal return numberFormatter. string(from: NSNumber(value:self))! } }


2 Answers

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) 
like image 96
Özgür Ersil Avatar answered Sep 19 '22 17:09

Özgür Ersil


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() 
like image 38
Juan Fran Jimenez Avatar answered Sep 21 '22 17:09

Juan Fran Jimenez