Java-带小数的计算器

Java-带小数的计算器,java,calculator,decimal,Java,Calculator,Decimal,我正在用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 这是可行的

我正在用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

这个问题有没有一个简单的解决方案,或者用另一种方法实现小数


提前谢谢

没关系,我自己用大小数找到了一个解决方案

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

BigDecimal bd = new BigDecimal(currentVal);
bd = bd.setScale(decPoints, BigDecimal.ROUND_HALF_UP);
currentVal = bd.doubleValue();

你的意思是3.369显示为3.36899999…?是的,对不起,这里的措辞很糟糕。这只适用于少数精心选择的值。您应该始终使用
大小数