如何解决 Java 四舍五入问题 [英] How to resolve a Java Rounding Double issue

查看:15
本文介绍了如何解决 Java 四舍五入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎减法引发了某种问题,结果值是错误的.

Seems like the subtraction is triggering some kind of issue and the resulting value is wrong.

double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d;

78.75 = 787.5 * 10.0/100d

78.75 = 787.5 * 10.0/100d

double netToCompany = targetPremium.doubleValue() - tempCommission;

708.75 = 787.5 - 78.75

708.75 = 787.5 - 78.75

double dCommission = request.getPremium().doubleValue() - netToCompany;

877.8499999999999 = 1586.6 - 708.75

877.8499999999999 = 1586.6 - 708.75

最终的预期值为 877.85.

The resulting expected value would be 877.85.

应该怎样做才能确保计算正确?

What should be done to ensure the correct calculation?

推荐答案

要控制浮点运算的精度,您应该使用 java.math.BigDecimal.阅读 John Zukowski 撰写的 BigDecimal 的需要,了解更多信息.

To control the precision of floating point arithmetic, you should use java.math.BigDecimal. Read The need for BigDecimal by John Zukowski for more information.

以您的示例为例,使用 BigDecimal 的最后一行如下所示.

Given your example, the last line would be as following using BigDecimal.

import java.math.BigDecimal;

BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);

结果如下.

877.85 = 1586.6 - 708.75

这篇关于如何解决 Java 四舍五入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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