BigDecimal Subtraction

元气小坏坏 提交于 2019-12-04 03:27:54

BigDecimal.valueOf(double d) uses canonical String representation of double value, internally Double.toString(double) is used, that's why you are getting 0.9 in second case.

Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double).

While with new BigDecimal(0.9) it converts value to exact floating point representation of double value without using String representation,

Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value.

...

NOTES :

  1. The results of this constructor can be somewhat unpredictable.

...

FOR EXAMPLE :

BigDecimal bd1 = new BigDecimal(Double.toString(0.9));
BigDecimal bd2 = new BigDecimal(0.9);
System.out.println(bd1);
System.out.println(bd2);

OUTPUT :

0.9
0.90000000000000002220446049250313080847263336181640625

Just for those others that got here looking for some other issue with BigDecimal(not related to the question above)... remember to give a mathContext to the methods to avoid certain problems e.g.

        MathContext mc = new MathContext(10, RoundingMode.HALF_UP);
        BigDecimal hitRate = new BigDecimal(totalGetValuesHitted).divide(new BigDecimal(totalGetValuesRequested), mc);
        BigDecimal missRate = new BigDecimal(1.0, mc).subtract(hitRate, mc);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!