NumberFormatter for a large number

I am trying this code to convert string to number and vice versa. this code should print the same outputs. but his conclusion is incorrect. can anyone help me?

let formatter: NumberFormatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US")


if let r1 = formatter.number(from: "10123456789012349") , let r2 = formatter.string(from:r1){

     print(r1) // output = 10123456789012349
     print(r2) // output = 10123456789012348
}

      

also this code has the same problem

print(formatter.string(from:NSNumber(value: 10123456789012349)))
//output is 10123456789012348

      

+3


source to share


1 answer


NumberFormatter

creates Int64

when it parses the string in the example. This type can accurately represent a numeric value. But the formatter uses double arithmetic even for 64-bit integers to compute the string representation of a number. The double can be a maximum of 16 or 17 decimal digits. This leads to surprisingly different results.

You can avoid this by using Decimal

s:

let formatter: NumberFormatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.generatesDecimalNumbers = true

let r1 = formatter.number(from: "10123456789012349")
let r2 = formatter.string(from: r1!)
print(r1!) // 10123456789012349
print(r2!) // 10123456789012349

      



EDIT: using Decimal

for formatting is sufficient for accurate results:

let formatter: NumberFormatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US")
let d1 = 10123456789012349 as Decimal

print(formatter.string(from: d1 as NSNumber)!)

      

+4


source







All Articles