0

我正在使用 Java 制作计算器。一切正常,我现在正在尝试实现小数。我正在使用双打来存储数字。我有一个解决方案以下解决方案:

decPoints++; //decPoints holds the current number of numbers after the decimal point
currentVal = currentVal + (n/Math.pow(10, decPoints)); //n is the number that is to be added on

这可行,但是会导致舍入错误,例如 3.369 将变为 3.689999..

是否有解决此问题的简单方法或其他实现小数的方法?

提前致谢!

4

1 回答 1

-1

没关系,我自己使用 BigDecimals 找到了解决方案。

decPoints++;
currentVal = currentVal + (n/Math.pow(10, decPoints));

BigDecimal bd = new BigDecimal(currentVal);
bd = bd.setScale(decPoints, BigDecimal.ROUND_HALF_UP);
currentVal = bd.doubleValue();
于 2013-03-06T15:55:12.387 回答