double 计算 精度缺失解决方案(加上 2e-15或是1.2e-15 补充缺失精度)

/**
 * 由于两个double相乘,会引起精度的缺失,即使使用BigDecimal也不能解决
 * 比如:11.7*1.95 = 22.814999999999998(正确值应该为22.815) 所以四舍五入时变成22.81而不是22.82
 * 一个简单解决方法就是round时,加上2e-15或是1.2e-15作为精度缺失的补充
 */
double a = 11.7;
double b = 1.95;
BigDecimal cBigDecimal = new BigDecimal(11.7);
BigDecimal dBigDecimal = new BigDecimal(1.95);
double result = a * b;//这里得出的是22.814999999999998,正确的应该是:a * b = 22.815
System.out.println("两个double相乘:" + result); 
System.out.println("两个double相乘 再四舍五入:" + (double)Math.round(result*100)/100); 
System.out.println("两个BigDecimal相乘:" + cBigDecimal.multiply(dBigDecimal)); 
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("两个BigDecimal相乘 再四舍五入:" + df.format(cBigDecimal.multiply(dBigDecimal))); 
System.out.println("两个double相乘 + 1.2e-15:" + result+1.2e-15); 
Double roundDouble = new Double((double)Math.round((result+1.2e-15)*100)/100);
System.out.println("两个double相乘 + 1.2e-15 再四舍五入:" + roundDouble); 

System.out.println("两个double相乘 + 2e-15:" + result+2e-15); 
roundDouble = new Double((double)Math.round((result+2e-15)*100)/100);
System.out.println("两个double相乘 + 2e-15 再四舍五入:" + roundDouble);

System.out.println(Math.round(22.8149999999));
BigDecimal bd = new BigDecimal(22.8149999999);
System.out.println((double)Math.round(22.8149999999*100)/100);
System.out.println((double)Math.round(bd.doubleValue()*100)/100);
		
		
/*	打印结果:
两个double相乘:22.814999999999998
两个double相乘 再四舍五入:22.82
两个BigDecimal相乘:22.8149999999999980948572897432314081874842663966245602191426113114491869282574043609201908111572265625
两个BigDecimal相乘 再四舍五入:22.81
两个double相乘 + 1.2e-15:22.8149999999999981.2E-15
两个double相乘 + 1.2e-15 再四舍五入:22.82
两个double相乘 + 2e-15:22.8149999999999982.0E-15
两个double相乘 + 2e-15 再四舍五入:22.82
23
22.81
22.81
 */

你可能感兴趣的:(double 计算 精度缺失解决方案(加上 2e-15或是1.2e-15 补充缺失精度))