无效的浮点值 - swift 3 ios

Invalid Float value - swift 3 ios(无效的浮点值 - swift 3 ios)

本文介绍了无效的浮点值 - swift 3 ios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有核心数据存储,我在 Float 中的字段expensesAmount"标识.费用金额的值为 6.3.但是当我将它检索到如下变量expensesAmount"时,它变成了 6.30000019.所以我的总金额不正确.

I had core data storage, my field "expensesAmount" in Float identify. The value of expensesAmount is 6.3. But when I retrieve it to variable "expensesAmount" as below, it become 6.30000019. So my totalAmount is not correct.

有人可以帮忙吗?

let entity:NSManagedObject = data?.object(at: i) as! NSManagedObject                    
if let expensesAmount = entity.value(forKey: "expensesAmount") as? Float {                         
   totalAmount += expensesAmount                   
}

推荐答案

我认为这与 IEEE-754 标准如何表示浮点数有关.使用标准,即使使用双精度数,也不一定能精确表达所有带分数的数字.这与 Swift 无关.C 中的下一个小代码将重现您的问题.

I think this is related to how the floating point numbers are expressed with IEEE-754 standard. With the standard, not all kinds of numbers with fraction may necessarily be expressed precisely even with double. This is irrelevant to Swift. The next small code in C will reproduce your issue.

int main(int argc, char **argv) {
  float fval = 6.3f;
  double dval = 6.3;
  printf("%.10f : %.17f
", fval, dval);
  // 6.3000001907 : 6.29999999999999980
}

所以,如果您需要小数部分的真实精度,您需要考虑其他方式.

So, if you need the real accuracy in fractional part, you need to consider some other way.

我检查了 NSDecimalNumber,它按预期工作.这是一个例子:

EDITED: I checked with NSDecimalNumber and it's working as expected. Here is an example:

    let bval = NSDecimalNumber(string: "6.3")  // (1) 6.3
    let bval10 = bval.multiplying(by: 10.0)  // 63.0
    let dval = bval.doubleValue
    let dval10 = bval10.doubleValue
    print(String(format: "%.17f", dval))  // 6.29999999999999982
    print(String(format: "%.17f", dval10))  // (6) 63.00000000000000000
    let bval2 = NSDecimalNumber(mantissa: 63, exponent: -1, isNegative: false)
    print(bval2)  // 6.3
    let bval3 = NSDecimalNumber(mantissa: 123456789, exponent: -4, isNegative: true)
    print(bval3)  // -12345.6789

正如您在 (6) 处看到的,在 (1) 处转换​​ 6.3 时没有四舍五入.Note 63.0 可以用 float/double 精确表达.

As you can see at (6), there's no round off when converting 6.3 at (1). Note 63.0 can be precisely expressed w/ float/double.

这篇关于无效的浮点值 - swift 3 ios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:无效的浮点值 - swift 3 ios

基础教程推荐