Trying to create a Decimal (or NSDecimalNumber) out of the given Double value for MONEY calculations within my app. I am using Swift 4 in Xcode 10.
But it generates following values which are wrong.
let doubleVal: Double = 56.203
Decimal(doubleVal) // Wrong Answer: 56.20299999999998976
Decimal.init(doubleVal) // Again Wrong Answer: 56.20299999999998976
If I use the String initialization, that works correct.
Decimal(string: "56.203")! // Correct Decimal: 56.203
I remember had the same problem in java when work with BigDecimal if call constructor with a double value. E.g. new BigDecimal(double val)... So they have this extra method valueOf BigDecimal.valueOf(amount);
that creates correct BigDecimal out of the double.
How do I generate a Decimal out of a given Double value with Swift?