NumberFormatter的generateDecimalNumbers不起作用 [英] generatesDecimalNumbers for NumberFormatter does not work
问题描述
我的函数正在将字符串转换为十进制
func getDecimalFromString(_ strValue:String)-> NSDecimalNumber {
让formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
formatter.generatesDecimalNumbers = true
返回formatter.number(from:strValue)as吗? NSDecimalNumber ?? 0
}
但是它没有按预期工作。有时它会像这样返回
可选(8.300000000000001)
可选(8.199999999999999)
而不是8.3或8.2。在字符串中,我的值类似于 8.3或 8.2,但转换后的十进制不符合我的要求。有什么建议我做错了吗?
比较似乎是个错误
即使有 generateDecimalNumbers
设置为 true
,格式器
在内部生成二进制浮点数,而
不能表示小数恰好 8.2
。
还请注意(与文档相反), maximumFractionDigits <将字符串
解析为数字时,/ code>属性无效。
有一个简单的解决方案:使用
NSDecimalNumber(string:strValue)//或
NSDecimalNumber(string:strValue,语言环境:Locale.current)
取决于字符串是否已本地化。 / p>
或使用Swift 3 十进制
类型:
Decimal(string:strValue)//或
Decimal(string:strValue,语言环境:.current)
例如:
如果d =小数(字符串: 8.2) {
print(d)// 8.2
}
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)
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?
That seems to be a bug, compare
Even with generatesDecimalNumbers
set to true
, the formatter
produces a binary floating point number internally, and that cannot
represent decimal fractions like 8.2
precisely.
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.
Or with the Swift 3 Decimal
type:
Decimal(string: strValue) // or
Decimal(string: strValue, locale: .current)
Example:
if let d = Decimal(string: "8.2") {
print(d) // 8.2
}
这篇关于NumberFormatter的generateDecimalNumbers不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!