如何在java中修复双精度问题 [英] how to fix double precision issue in java
问题描述
如何克服双精度问题请注意,我将字符串值转换为双精度值。
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 ,以避免任何精度问题,并始终使用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") );
这篇关于如何在java中修复双精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!