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 不起作用
基础教程推荐
- 固定小数的Android Money Input 2022-01-01
- “让"到底是怎么回事?关键字在 Swift 中的作用? 2022-01-01
- Android ViewPager:在 ViewPager 中更新屏幕外但缓存的片段 2022-01-01
- LocationClient 与 LocationManager 2022-01-01
- 使用 Ryzen 处理器同时运行 WSL2 和 Android Studio 2022-01-01
- Android文本颜色不会改变颜色 2022-01-01
- :hover 状态不会在 iOS 上结束 2022-01-01
- 如何使 UINavigationBar 背景透明? 2022-01-01
- 如何使用 YouTube API V3? 2022-01-01
- 在 iOS 上默认是 char 签名还是 unsigned? 2022-01-01
