Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading