Invalid Float value - swift 3 ios

前端 未结 2 1117
闹比i
闹比i 2021-01-25 00:16

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 b

相关标签:
2条回答
  • 2021-01-25 00:21

    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.

    0 讨论(0)
  • 2021-01-25 00:42

    Try Follwoing :

    let entity:NSManagedObject = data?.object(at: i) as! NSManagedObject
    
    if let expensesAmount = entity.value(forKey: "expensesAmount") as? NSNumber {
    
    totalAmount += expensesAmount.floatValue
    
    }
    
    0 讨论(0)
提交回复
热议问题