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

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

问题描述

似乎减法会触发某种问题而结果值是错误的。

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 Rounding Double问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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