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
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 accure again if I try to convert Double to Decimal (with 024 on the end).
Do you have ideas what can be an approach in the situation?
There’s nothing wrong here. You’re encountering a fundamental property of floating point numbers: they can’t precisely represent all decimals. formatter.number(from: "579.988") is a lossy operation; the NSNumber object that is returned wraps the closest-representable floating point number.
Right, but the formatter still has maximumFractionDigits set to 3. It’s a bit surprising that it doesn’t respect that when producing a decimal value.