BigDecimal

例子:加减乘除(+-*/)

System.out.println(0.05 + 0.01);
System.out.println(1.0 - 0.42);
System.out.println(4.015 * 100);
System.out.println(123.3 / 100);

 运算结果:

0.060000000000000005
0.5800000000000001
401.49999999999994
1.2329999999999999

关于BigDecimal丢失精度的问题,声明BigDecimal对象的时候一定要使用它构造参数为String的类型的构造器

BigDecimal a1 = new BigDecimal(Double.toString(0.05));
BigDecimal a2 = new BigDecimal(Double.toString(0.01));
System.out.println(a1.add(a2));
BigDecimal b1 = new BigDecimal(Double.toString(1.0));
BigDecimal b2 = new BigDecimal(Double.toString(0.42));
System.out.println(b1.subtract(b2));
BigDecimal c1 = new BigDecimal(Double.toString(4.015));
BigDecimal c2 = new BigDecimal(Double.toString(100));
System.out.println(c1.multiply(c2));
BigDecimal d1 = new BigDecimal(Double.toString(123.3));
BigDecimal d2 = new BigDecimal(Double.toString(100));
System.out.println(d1.divide(d2, 2, BigDecimal.ROUND_HALF_UP));//应对除不尽的情况, 2 = 保留小数点后两位   ROUND_HALF_UP = 四舍五入

运算结果:

0.06
0.58
401.5000
1.23

  

posted on 2020-05-26 23:11  陌生街中吹起褪色故梦  阅读(188)  评论(0编辑  收藏  举报