问题描述
我知道float或double不能很好地存储货币和数量等十进制数字.我正在尝试使用NSDecimalNumber代替.这是我在Swift操场上的代码.
I know float or double are not good for storing decimal number like money and quantity. I'm trying to use NSDecimalNumber instead. Here is my code in Swift playground.
let number:NSDecimalNumber = 1.66
let text:String = String(describing: number)
NSLog(text)
控制台输出为1.6599999999999995904
The console output is 1.6599999999999995904
如何将十进制数字1.66的确切值存储在变量中?
How can I store the exact value of the decimal number 1.66 in a variable?
推荐答案
在
let number:NSDecimalNumber = 1.66
右侧是一个浮点数,不能表示值"1.66"正好.一种选择是创建十进制数从字符串:
the right-hand side is a floating point number which cannot representthe value "1.66" exactly. One option is to create the decimal numberfrom a string:
let number = NSDecimalNumber(string: "1.66")
print(number) // 1.66
另一种选择是使用算术:
Another option is to use arithmetic:
let number = NSDecimalNumber(value: 166).dividing(by: 100)
print(number) // 1.66
在Swift 3中,您可以考虑使用覆盖值类型" Decimal
,例如
With Swift 3 you may consider to use the "overlay value type" Decimal
instead, e.g.
let num = Decimal(166)/Decimal(100)
print(num) // 1.66
另一个选择:
let num = Decimal(sign: .plus, exponent: -2, significand: 166)
print(num) // 1.66
附录:
Swift论坛中的相关讨论:
Related discussions in the Swift forum:
- Exact NSDecimalNumber via literal
- ExpressibleByFractionLiteral
相关的错误报告:
- SR-3317Literal protocol for decimal literals should support precise decimal accuracy, closed as a duplicate of
- SR-920Re-design builtin compiler protocols for literal convertible types.
这篇关于如何在NSDecimalNumber中存储1.66的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!