how to add commas to a number in 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.


Solution 1:

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)

Solution 2:

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()

Solution 3:

Also expanding on Juan Fran Jimenez's answer, I would recommend putting the formatter into a singleton, since instantiating a formatter is usually a relatively expensive operation. (It could affect the performance if you're formatting on-the-go as the user writes.)

extension Int {

    private static var commaFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()

    internal var commaRepresentation: String {
        return Int.commaFormatter.string(from: NSNumber(value: self)) ?? ""
    }
}

Solution 4:

A simple drop in extension that will provide a variable via an extension of Int.

As noted in Julien's answer, this makes use of a static formatter for performance reasons.

extension Int {
    private static var numberFormatter: NumberFormatter = {
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal

        return numberFormatter
    }()

    var delimiter: String {
        return Int.numberFormatter.string(from: NSNumber(value: self)) ?? ""
    }
}

To use it:

let number = 31908551587
print(number.delimiter) // 31,908,551,587