对于Java的float和double类型,都存在精度损失的问题。
精度损失产生的原因在于Java的数据存储采用的都是2进制形式,二进制不能准确的表示1/10等分数,只能无限趋近。
public static void main(String[] args){ float a = (float) 1.0; float b = (float) 0.965; double a1 = 1.0; double b1 = 0.965; BigDecimal a2 = new BigDecimal(a1); BigDecimal b2 = new BigDecimal(b1); BigDecimal a3 = new BigDecimal(new String("1.0")); BigDecimal b3 = new BigDecimal(new String("0.965")); System.out.println("float:"+(a-b)); System.out.println("double:"+(a1-b1)); System.out.println("BigDecimal use Double:"+a2.subtract(b2)); System.out.println("BigDecimal use String:"+a3.subtract(b3)); }
运行结果如下:
float:0.035000026
double:0.03500000000000003
BigDecimal use Double:0.03500000000000003108624468950438313186168670654296875
BigDecimal use String:0.035
程序运行结果如下:
程序运行结果如下:
标签:动脑,BigDecimal,double,float,动手,课后,new,out,String From: https://www.cnblogs.com/binglinll/p/17707076.html