解决double类型计算时丢失精度问题
问题:double类型在进行计算时可能会丢失精度
double v1 = 0.2;
double v2 = 0.3;
double v3 = v2 - v1;
预期:v3=0.1
实际:v3=0.09999999999999998
解决:用BigDecimal类型包装一下数据然后计算(需要先把数据转为String类型!)
不转为String类型:
double v1 = 0.2;
double v2 = 0.3;
double v3 = v2 - v1;
BigDecimal b1 = new BigDecimal(v1);
BigDecimal b2 = new BigDecimal(v2);
double b3 = b2.subtract(b1).doubleValue();
b3=0.09999999999999998
正确方式:
double v1 = 0.2;
double v2 = 0.3;
double v3 = v2 - v1;
BigDecimal s1 = new BigDecimal(String.valueOf(v1));
BigDecimal s2 = new BigDecimal(String.valueOf(v2));
double s3 = s2.subtract(s1).doubleValue();
代码示例:
public static void main(String[] args) { double v1 = 0.2; double v2 = 0.3; double v3 = v2 - v1; System.out.println("v3:" + v3); System.out.println("-------------"); BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(v2); double b3 = b2.subtract(b1).doubleValue(); System.out.println("b3:" + b3); System.out.println("-------------"); BigDecimal s1 = new BigDecimal(String.valueOf(v1)); BigDecimal s2 = new BigDecimal(String.valueOf(v2)); double s3 = s2.subtract(s1).doubleValue(); System.out.println("s3:" + s3); }
v3:0.09999999999999998 ------------- b3:0.09999999999999998 ------------- s3:0.1