我总是被告知永远不要用双类型或浮点类型来表示货币,这一次我向你提出一个问题:为什么?

我相信有一个很好的理由,我只是不知道是什么。


当前回答

我将冒着被否决的风险,但我认为浮点数在货币计算中的不适用性被高估了。只要确保正确地进行了舍入,并且有足够的有效数字来处理zneak解释的二进制十进制表示不匹配,就不会有问题。

在Excel中使用货币计算的人总是使用双精度浮点数(Excel中没有货币类型),我还没有看到有人抱怨舍入错误。

当然,你必须在合理范围内;例如,一个简单的网络商店可能永远不会遇到双精度浮点数的任何问题,但如果你做会计或其他需要添加大量(无限制)数字的事情,你不会想要用十英尺的杆子触摸浮点数。

其他回答

美国货币可以很容易地用美元和美分来表示。整数是100%精确的,而浮点二进制数并不完全匹配浮点小数。

为了补充前面的答案,在处理问题中解决的问题时,除了BigDecimal之外,还可以选择在Java中实现Joda-Money。Java模块名称为org.joda.money。

它需要Java SE 8或更高版本,并且没有依赖关系。

更准确地说,存在编译时依赖关系,但它不是 必需的。

<dependency>
  <groupId>org.joda</groupId>
  <artifactId>joda-money</artifactId>
  <version>1.0.1</version>
</dependency>

使用Joda Money的例子:

  // create a monetary value
  Money money = Money.parse("USD 23.87");
  
  // add another amount with safe double conversion
  CurrencyUnit usd = CurrencyUnit.of("USD");
  money = money.plus(Money.of(usd, 12.43d));
  
  // subtracts an amount in dollars
  money = money.minusMajor(2);
  
  // multiplies by 3.5 with rounding
  money = money.multipliedBy(3.5d, RoundingMode.DOWN);
  
  // compare two amounts
  boolean bigAmount = money.isGreaterThan(dailyWage);
  
  // convert to GBP using a supplied rate
  BigDecimal conversionRate = ...;  // obtained from code outside Joda-Money
  Money moneyGBP = money.convertedTo(CurrencyUnit.GBP, conversionRate, RoundingMode.HALF_UP);
  
  // use a BigMoney for more complex calculations where scale matters
  BigMoney moneyCalc = money.toBigMoney();

文档: http://joda-money.sourceforge.net/apidocs/org/joda/money/Money.html 实现示例: https://www.programcreek.com/java-api-examples/?api=org.joda.money.Money

大多数回答都强调了为什么不应该使用替身来计算金钱和货币。我完全同意他们的观点。

但这并不是说,double永远不能用于这个目的。

我曾经参与过许多gc需求非常低的项目,BigDecimal对象是造成这种开销的一个重要因素。

正是由于缺乏对双重表示的理解,以及缺乏处理准确性和精确性的经验,才产生了这个明智的建议。

如果您能够处理项目的精度和准确性要求,则可以使其工作,这必须基于处理的双精度值的范围来完成。

你可以参考番石榴的FuzzyCompare方法来获得更多的信息。参数公差是关键。 我们为一个证券交易应用程序处理了这个问题,并对在不同范围内对不同数值使用什么公差做了详尽的研究。

此外,在某些情况下,您可能会试图使用Double包装器作为映射键,并将哈希映射作为实现。这是非常危险的,因为双重。等号和哈希码,例如值“0.5”和“0.6 - 0.1”将导致一个大混乱。

The result of floating point number is not exact, which makes them unsuitable for any financial calculation which requires exact result and not approximation. float and double are designed for engineering and scientific calculation and many times doesn’t produce exact result also result of floating point calculation may vary from JVM to JVM. Look at below example of BigDecimal and double primitive which is used to represent money value, its quite clear that floating point calculation may not be exact and one should use BigDecimal for financial calculations.

    // floating point calculation
    final double amount1 = 2.0;
    final double amount2 = 1.1;
    System.out.println("difference between 2.0 and 1.1 using double is: " + (amount1 - amount2));

    // Use BigDecimal for financial calculation
    final BigDecimal amount3 = new BigDecimal("2.0");
    final BigDecimal amount4 = new BigDecimal("1.1");
    System.out.println("difference between 2.0 and 1.1 using BigDecimal is: " + (amount3.subtract(amount4)));

输出:

difference between 2.0 and 1.1 using double is: 0.8999999999999999
difference between 2.0 and 1.1 using BigDecimal is: 0.9

浮点数和双精度数是近似的。如果你创建了一个BigDecimal并将一个float传递给构造函数,你会看到float实际等于什么:

groovy:000> new BigDecimal(1.0F)
===> 1
groovy:000> new BigDecimal(1.01F)
===> 1.0099999904632568359375

这可能不是您想要的表示1.01美元的方式。

问题是IEEE规范没有一种方法来精确地表示所有的分数,其中一些分数最终是重复的分数,所以你最终会得到近似错误。由于会计人员喜欢精确到每一分钱,如果客户支付账单,在付款处理后他们欠0.01,他们会被收取费用或无法关闭他们的帐户,那么最好使用精确的类型,如decimal(在c#中)或Java. math. bigdecimal。

这并不是说如果你四舍五入,误差就无法控制:请参阅Peter Lawrey的这篇文章。只是从一开始就不用四舍五入更容易。大多数处理资金的应用程序不需要大量的数学运算,操作包括添加东西或将金额分配到不同的存储空间。引入浮点数和舍入只会使事情复杂化。