Invalid Float value - 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
基础教程推荐
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01