四舍五入到最接近的整数



我正在编写一个函数,它应该返回已四舍五入到最接近的向上磅(£)的总金额。注:输入的是没有小数点的整数,因此260实际上是£2.60等等。

intput: 260 -> output: 0.40
intput: 520 -> output: 0.80
total = 1.20 (because 40p + 80p)

我已经写出了这个函数:

public Double nearestPoundTotaler(List<Integer> transactions)
{
double total = 0.00;
for(Integer amount : transactions)
{
int penceAmount = amount % 100;
int penceToNearestNextPound = 100 - penceAmount;
double answer = penceToNearestNextPound / 100.0;
total = total + answer;
}
return total;
}

我写了单元测试,逻辑工作,但测试失败,因为小数点不正确。例如,如果将260,260,260传递到方法中,我将得到以下内容:

expected: 1.2
but was: 1.2000000000000002

我试了很多方法来去掉小数点,但我似乎还没有找到方法。也有可能在Java中使用.round()方法执行此逻辑吗?

由于数值问题,原始类型double不能表示精确的数字。尝试使用BigDecimal和.divide()方法代替。您还可以将比例设置为2(小数点后2位)和RoundingMode(通常为HALF_UP)

最新更新