我必须将我的结果四舍五入到0.05即(6.34到6.35和6.37到6.4) 所以我创建了myRound函数。 当我写测试看功能,它失败。在JAVA双精度
double rate=14.99;
double percentage=10;
double roundedCost=(rate*percentage)/100; //round off to the nearest value.
double finalRate = rate+myRound(roundedCost,2);
if(finalRate==16.49)
System.out.println("Its proper");
else
System.out.println("Wrong");
原因是双精度的准确值。 如何更正精度。
public double myRound(double value,int roundRange)
{
double hundredMultiple=(float) Math.pow(10, roundRange);
int rangeValue= (int) (value*hundredMultiple);
int tempValue= rangeValue%10;
if(tempValue<5)
tempValue=5-tempValue;
else
tempValue=10-tempValue;
rangeValue=rangeValue+tempValue;
return rangeValue/hundredMultiple;
}
使用'BigDecimal' –
阅读http://floating-point-gui.de/以了解问题的根源和可能的修复方法。 –