两个float相减时丢失精度的解决方法

通常我们习惯这么写:

       float a = 2.123f;   

       float b = 1.101f;   

       System.out.println("a-b=" + (a-b));

       运行结果:a-b=1.022

那么这么写呢?

       a = 2.1235f;   

       b = 1.1012f;   

       System.out.println("a-b=" + (a-b));

       运行结果:a-b=1.0223001

       可我们的期望值是:a-b=1.0223

所以float的精度到了4位之后就得这么写:

       BigDecimal c = new BigDecimal(Float.toString(a));   

       BigDecimal d = new BigDecimal(Float.toString(b));   

       System.out.println("a-b=" + (c.subtract(d)).floatValue());

       运行结果:a-b=1.0223

============================================================================================

//两个BigDecimal相加
  big1 = big1.add(big2);
  System.out.println(big1);
  //两个BigDecimal相减
  big1 = big1.subtract(big2);
  System.out.println(big1);
  //两个BigDecimal相乘
  big1 = big1.multiply(big2);
  System.out.println(big1);
  //两个BigDecimal相除
  big1 = big1.divide(big2);
  System.out.println(big1);

你可能感兴趣的:(java)