Home > Blockchain >  Why does NumberFormatter format 19,999,999,999,999,999 to 20,000,000,000,000,000 in Swift?
Why does NumberFormatter format 19,999,999,999,999,999 to 20,000,000,000,000,000 in Swift?

Time:11-07

I need to separate Int values with commas every 3 digits in Swift.
I have tried to do this with NumberFormatter, but it sometimes returns unexpected results with large digits.
Why is this?

import Foundation

func format(_ num: Int) -> String {
  let formatter = NumberFormatter()
  formatter.numberStyle = .decimal
  formatter.groupingSeparator = ","
  formatter.groupingSize = 3
  return formatter.string(from: NSNumber(value: num)) ?? String(num)
}

let num1 =       199_999_999_999_999
let num2 =     1_999_999_999_999_999
let num3 =    19_999_999_999_999_999
let num4 =   199_999_999_999_999_999
let num5 = 1_999_999_999_999_999_999

print(format(num1))
print(format(num2))
print(format(num3))
print(format(num4))
print(format(num5))

// 199,999,999,999,999
// 1,999,999,999,999,999
// 20,000,000,000,000,000 <- unexpected results
// 199,999,999,999,999,999
// 1,999,999,999,999,999,999

CodePudding user response:

It's a bug in NumberFormatter. (There are many.) Try printing Decimal(19_999_999_999_999_999).formatted() instead.

  • Related