什么时候使用NSDecimal,NSDecimalNumber而不是double更好? [英] When is it better to use an NSDecimal, NSDecimalNumber instead of a double?

查看:148
本文介绍了什么时候使用NSDecimal,NSDecimalNumber而不是double更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于简单的用途(例如跟踪65.1kg之类的重量值),使用NSDecimal/NSDecimalNumber超过两倍有什么好处吗?

For simple uses, such as tracking weight values like 65.1kg, is there any benefit of going with NSDecimal/NSDecimalNumber over double?

我在这里的理解是,在这种情况下,双精度(甚至是浮点数)提供了足够的精度.如果我错了,请纠正我.

My understanding here is double (or even float) provides more than enough precision in such cases. Please correct me if I'm wrong.

推荐答案

首先,阅读Josh Caswell的链接.当与钱一起工作时,这一点尤其重要.对于您而言,这可能很重要,也可能无关紧要,具体取决于您的目标.如果输入65.1并希望精确返回65.1,则肯定需要使用正确舍入到小数点值的格式,例如NSDecimalNumber.如果在输入65.1时想要一个在65.1的小错误范围内的值",那么float或double都可以(取决于您愿意接受的错误量).

First, read Josh Caswell's link. It it especially critical when working with money. In your case it may matter or may not, depending on your goal. If you put in 65.1 and you want to get exactly 65.1 back out, then you definitely need to use a format that rounds properly to decimal values like NSDecimalNumber. If, when you put in 65.1, you want "a value that is within a small error of 65.1," then float or double are fine (depending on how much error you are willing to accept).

65.1是一个很好的例子,因为它说明了问题.在Swift中使用它是因为它很容易演示,但是ObjC是相同的:

65.1 is a great example, because it demonstrates the problem. Here in Swift because its so easy to demonstrate, but ObjC is the same:

 1> 65.1
$R0: Double = 65.099999999999994
  2>

1/10恰好是二进制的重复小数,就像1/3是十进制的重复小数一样.因此,编码为double的65.1与65.1接近",但不精确.如果您需要精确表示十进制编码的数字(即大多数人期望的数字),请使用NSDecimalNumber.这并不是说NSDecimalNumber比double更为准确.它所施加的舍入误差与加倍误差不同.您更喜欢哪种舍入错误取决于您的用例.

1/10 happens to be a repeating decimal in binary, just like 1/3 is a repeating decimal in decimal. So 65.1 encoded as a double is "close to" 65.1, but not exact. If you need an exact representation of decimal-encoded number (i.e. what most humans expect), use NSDecimalNumber. This isn't to say that NSDecimalNumber is more accurate than double. It just imposes different rounding errors than double. Which rounding errors you prefer depends on your use case.

这篇关于什么时候使用NSDecimal,NSDecimalNumber而不是double更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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