Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Double conversion loses precision in Swift

I want to covert a string to double and keep the same value:

let myStr = "2.40"
let numberFormatter = NSNumberFormatter()
numberFormatter.locale = NSLocale(localeIdentifier: "fr_FR")
let myDouble = numberFormatter.numberFromString(myStr)?.doubleValue ?? 0.0

myDouble is now

Double? 2.3999999999999999

So how to convert "2.40" to exact be 2.40 as Double ??

Update:

Even rounding after conversion does not seem to work

I don't want to print, I want to calculate and it's important that the number should be correct, it's Money calculation and rates

like image 869
iOSGeek Avatar asked Apr 29 '16 10:04

iOSGeek


1 Answers

First off: you don't! What you encountered here is called floating point inaccuracy. Computers cannot store every number precisely. 2.4 cannot be stored lossless within a floating point type.

Secondly: Since floating point is always an issue and you are dealing with money here (I guess you are trying to store 2.4 franc) your number one solution is: don't use floating point numbers. Use the NSNumber you get from the numberFromString and do not try to get a Double out of it.
Alternatively shift the comma by multiplying and store it as Int.

The first solutions might look something like:

if let num = myDouble {
    let value = NSDecimalNumber(decimal: num.decimalValue)
    let output = value.decimalNumberByMultiplyingBy(NSDecimalNumber(integer: 10))
}
like image 185
luk2302 Avatar answered Oct 20 '22 22:10

luk2302