Invalid Float value - swift 3 ios

五迷三道 提交于 2019-12-20 04:48:14

问题


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.

Can someone help?

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

回答1:


Try Follwoing :

let entity:NSManagedObject = data?.object(at: i) as! NSManagedObject

if let expensesAmount = entity.value(forKey: "expensesAmount") as? NSNumber {

totalAmount += expensesAmount.floatValue

}



回答2:


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\n", fval, dval);
  // 6.3000001907 : 6.29999999999999980
}

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

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

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.



来源:https://stackoverflow.com/questions/40648479/invalid-float-value-swift-3-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!