如何修复Java双precision问题问题、Java、precision

2023-09-12 10:25:35 作者:年轻就是资本

可能重复:   Java花车和双打,如何避免0.0 + 0.1 +… + 0.1 = = 0.9000001?

我怎样才能克服precision问题在Java的Andr​​oid双倍增?请注意,我将一个字符串值转换成double值。

How can I overcome the precision issue with double multiplication in java android??Please note that I am converting a string value into double value.

例如:当我将两个双精度值:

eg: when I multiply two double value:

double d1 = Double.valueOf("0.3").doubleValue() * Double.valueOf("3").doubleValue();
System.out.println("Result of multiplication : "+d1);

我得到以下结果:0.8999999999999999

I am getting the following result : 0.8999999999999999

一些我得到的结果是。

0.6 * 3 = 1.7999999999999998;   0.2 * 0.2 = 0.04000000000000001;   等等。

0.6*3=1.7999999999999998; 0.2*0.2=0.04000000000000001; etc.

我希望得到下面的结果。

Instead of the above results I would like to get the following results.

0.3 * 3 = 0.9;   0.6 * 3 = 1.8;   0.2 * 0.2 = 0.04;

0.3*3=0.9; 0.6*3=1.8; 0.2*0.2=0.04;

请记住,我不是把它四舍五入到最接近的整数。

Please remember that I am not trying to round it to the nearest integer.

推荐答案

您真的应该使用的Java。 math.BigDecimal ,以避免任何precision问题,并始终用一个BigDecimal(String)构造。

You should really be using java.math.BigDecimal to avoid any precision issues, and always use a BigDecimal(String) constructor.

BigDecimal result = new BigDecimal("0.3").multiply( new BigDecimal("3.0") );