如何解决Java舍入双重问题似乎减法触发了某种问题,其结果是错误的。double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d;78.75=787.5*10.0/100 ddouble netToCompany = targetPremium.doubleValue() - tempCommission;708.75 = 787.5 - 78.75double dCommission = request.getPremium().doubleValue() - netToCompany;877.8499999999999 = 1586.6 - 708.75由此产生的期望值为877.85。如何确保计算正确?
3 回答
千万里不及你
TA贡献1784条经验 获得超9个赞
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
凤凰求蛊
TA贡献1825条经验 获得超4个赞
java.math.BigDecimal
.
BigDecimal
BigDecimal
BigDecimal(double)
BigDecimal.valueOf(double)
double
BigDecimal
String
BigDecimal
.
BigDecimal
double value = 0.585; System.out.println(new BigDecimal(value)); System.out.println(BigDecimal.valueOf(value));
0.58499999999999996447286321199499070644378662109375 0.585
绝地无双
TA贡献1946条经验 获得超4个赞
double d = 0;for (int i = 1; i <= 10; i++) { d += 0.1;}System.out.println(d); // prints 0.9999999999999999 not 1.0
添加回答
举报
0/150
提交
取消