问题描述
我有核心的数据存储,我的领域费用安装在Float识别。expensesAmount的值是6.3。
但是,当我将其检索到变量expensesAmount,如下所示,它变成了6.30000019。
所以我的totalAmount是不正确的。
有人可以帮忙吗?
let entity:NSManagedObject = data?.object(at:i)as! NSManagedObject
如果让expenseAmount = entity.value(forKey:expenseAmount)为? Float {
totalAmount + = expensesAmount
}
int main(int argc,char ** argv){
float fval = 6.3f;
double dval = 6.3;
printf(%。10f:%.17f\\\
,fval,dval);
// 6.3000001907:6.29999999999999980
}
所以,如果你需要真正的准确性在小数部分,您需要考虑一些其他方式。
编辑:
我检查了NSDecimalNumber和它的工作正常。这里是一个例子:
pre $ let $ b $ = NSDecimalNumber(string:6.3)//(1)6.3
让bval10 = bval.multiplying(by:10.0)// 63.0
let dval = bval.doubleValue
let dval10 = bval10.doubleValue
print(String(format:%.17f, (尾数:63,指数:-1,isNegative)// 6.29999999999999982
print(String(format:% :false)
print(bval2)// 6.3
let bval3 = NSDecimalNumber(尾数:123456789,指数:-4,isNegative:true)
print(bval3)// -12345.6789 $ b (6)中可以看到,在(1)中转换6.3时没有四舍五入的结果。注意63.0可以用w / float / double精确表示。
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
}
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.
这篇关于无效的浮点值 - swift 3 ios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!