How to store 1.66 in NSDecimalNumber

人盡茶涼 提交于 2019-12-17 04:07:54

问题


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)

The console output is 1.6599999999999995904

How can I store the exact value of the decimal number 1.66 in a variable?


回答1:


In

let number:NSDecimalNumber = 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

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

Yet another option:

let num = Decimal(sign: .plus, exponent: -2, significand: 166)
print(num) // 1.66

Addendum:

Related discussions in the Swift forum:

  • Exact NSDecimalNumber via literal
  • ExpressibleByFractionLiteral

Related bug reports:

  • SR-3317 Literal protocol for decimal literals should support precise decimal accuracy, closed as a duplicate of
  • SR-920 Re-design builtin compiler protocols for literal convertible types.


来源:https://stackoverflow.com/questions/42781785/how-to-store-1-66-in-nsdecimalnumber

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!