我的函数是将字符串转换为十进制
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:
NSDecimalNumber
s from NSNumberFormatter
受二进制逼近影响错误NSDecimalNumber
s from NSNumberFormatter
are 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 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!