Swift NumberFormatter gives incorrect values with lots of extra zeros

74 Views Asked by At

I found that for some strings the NumberFormatter produces incorrect results, as in the example below.

let input = "579.988"

let formatter = NumberFormatter()
formatter.maximumFractionDigits = 3
formatter.numberStyle = .decimal
formatter.decimalSeparator = "." // added to make it reproducible for everyone

let output = formatter.number(from: input)?.decimalValue

Result: 579.9880000000001

The error also appears for other strings. For example, "589.988". The error can be reproduced in the playground and an application, for Swift versions 5.2, 4.2 at least.

The NumberFormatter property doubleValue produces correct results, at least for strings that I tested; but the problem occurs again if I try to convert Double to Decimal (with 024 on the end).

Do you have ideas how I can approach this situation?

1

There are 1 best solutions below

0
soundflix On

You are facing a rounding error problem.

I would look at it from the practical side, which of course depends on what you are doing with those numbers.

Leave your string to decimal conversion as it is. Then, whenever you are displaying your numbers, there will be a conversion back to string anyways.
In Swift 5, there's the formatted(_:) method, which is easy to use:

numberValue.formatted() // "579.988"

If you'd like to fix the displayed fraction digits length, use this:

numberValue?.formatted(.number.precision(.fractionLength(4))) // "579.9880"