如何在 NSDecimalNumber 中存储 1.66 [英] How to store 1.66 in NSDecimalNumber
问题描述
我知道 float 或 double 不适合存储十进制数,如货币和数量.我正在尝试使用 NSDecimalNumber 代替.这是我在 Swift playground 中的代码.
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?
推荐答案
In
let number:NSDecimalNumber = 1.66
右边是不能表示的浮点数值1.66".一种选择是创建十进制数来自一个字符串:
the right-hand side is a floating point number which cannot represent the value "1.66" exactly. One option is to create the decimal number from 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:
相关错误报告:
这篇关于如何在 NSDecimalNumber 中存储 1.66的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!