[SOLVED] Large decimal number formatting using NumberFormatter in Swift

Issue

I’ve done this to format the number, but it fails for large numbers

let formatter = NumberFormatter()
formatter.numberStyle = .decimal


    if let number = formatter.number(from: "123456789123456789123") , let str = formatter.string(from:number){

        print(number)
        print(str)
    }

It prints

123456789123456800000
123,456,789,123,456,800,000

It should print

123456789123456789123
123,456,789,123,456,789,123

I think there should be the number overflow, is there any alternative to achieve this kind of thing.

Solution

You could create a Decimal explicitly to work around the mentioned bug

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
if let decimalNumber = Decimal(string: "123456789123456789123"), let str = formatter.string(from:decimalNumber as NSNumber) {
    print(decimalNumber)
    print(str)
}

Answered By – vadian

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.