generatesDecimalNumbers for NumberFormatter does not work(NumberFormatter 的 generateDecimalNumbers 不起作用)
问题描述
我的函数是将字符串转换为十进制
My function is converting a string to Decimal
func getDecimalFromString(_ strValue: String) -> NSDecimalNumber {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.generatesDecimalNumbers = true
return formatter.number(from: strValue) as? NSDecimalNumber ?? 0
}
但它没有按预期工作.有时它会像这样返回
But it is not working as per expectation. Sometimes it's returning like
Optional(8.300000000000001)
Optional(8.199999999999999)
而不是 8.3 或 8.2.在字符串中,我有类似8.3"或8.2"的值,但转换后的小数不符合我的要求.有什么建议我犯错了吗?
instead of 8.3 or 8.2. In the string, I have value like "8.3" or "8.2" but the converted decimal is not as per my requirements. Any suggestion where I made mistake?
推荐答案
将 generatesDecimalNumbers 设置为 true 并不像预期的那样工作.返回的值是 NSDecimalNumber 的一个实例(可以准确地表示值 8.3),但显然格式化程序首先将字符串转换为二进制浮点数(并且可以不准确地表示 8.3).因此返回的十进制值只是大致正确.
Setting generatesDecimalNumbers to true does not work as one might expect. The returned value is an instance of NSDecimalNumber (which can represent the value 8.3 exactly), but apparently the formatter converts the string to a binary floating number first (and that can not represent 8.3 exactly). Therefore the returned decimal value is only approximately correct.
这也被报告为一个错误:
That has also been reported as a bug:
NSDecimalNumbers fromNSNumberFormatter受二进制逼近影响错误
NSDecimalNumbers fromNSNumberFormatterare affected by binary approximation error
还要注意(与文档相反),maximumFractionDigits 属性在 解析 字符串时不起作用变成一个数字.
Note also that (contrary to the documentation), the maximumFractionDigits property has no effect when parsing a string
into a number.
有一个简单的解决方案:使用
There is a simple solution: Use
NSDecimalNumber(string: strValue) // or
NSDecimalNumber(string: strValue, locale: Locale.current)
相反,取决于字符串是否本地化.
instead, depending on whether the string is localized or not.
或者使用 Swift 3 Decimal 类型:
Or with the Swift 3 Decimal type:
Decimal(string: strValue) // or
Decimal(string: strValue, locale: .current)
例子:
if let d = Decimal(string: "8.2") {
print(d) // 8.2
}
这篇关于NumberFormatter 的 generateDecimalNumbers 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:NumberFormatter 的 generateDecimalNumbers 不起作用
基础教程推荐
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
