问题描述
似乎减法会触发某种问题而结果值是错误的。
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?
推荐答案
要控制浮点运算的精度,你应该使用。阅读John Zukowski的以获取更多信息。
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 Rounding Double问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!