問題描述
我有核心數據存儲,我在 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!