如何在NSDecimalNumber中存储1.66 [英] How to store 1.66 in NSDecimalNumber

查看:156
本文介绍了如何在NSDecimalNumber中存储1.66的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道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 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:

  • Exact NSDecimalNumber via literal
  • ExpressibleByFractionLiteral

相关的错误报告:

这篇关于如何在NSDecimalNumber中存储1.66的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆