简体   繁体   English

String to Double转换在Swift中失去了精度

[英]String to Double conversion loses precision in Swift

I want to covert a string to double and keep the same value: 我想将一个字符串转换为double并保持相同的值:

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

myDouble is now myDouble现在

Double? 2.3999999999999999

So how to convert "2.40" to exact be 2.40 as Double ?? 那么如何将“2.40”转换为精确到2.40为双?

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 我不想打印,我想计算,重要的是数字应该是正确的,这是货币计算和费率

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. 2.4浮点类型内无法存储无损。

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 . 其次:由于浮点始终是一个问题而你在这里处理钱(我猜你试图存储2.4法郎),你的头号解决方案是: 不要使用浮点数 Use the NSNumber you get from the numberFromString and do not try to get a Double out of it. 使用从numberFromString获得的NSNumber ,不要试图从中获取Double
Alternatively shift the comma by multiplying and store it as Int . 或者,将逗号移位并将其存储为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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM