BigDecimal Subtraction

感情迁移 提交于 2019-12-21 12:04:19

问题


I want to substract 2 double values, and I have tried the following code.

double val1 = 2.0;
double val2 = 1.10;

System.out.println(val1 - val2);

and I got the output as,

0.8999999999999999

For getting output as 0.9 I tried with BigDecimal as follows,

BigDecimal val1BD = new BigDecimal(val1);
BigDecimal val2BD = new BigDecimal(val2);

System.out.println(val1BD.subtract(val2BD));

And I got the output as,

0.899999999999999911182158029987476766109466552734375

Then I tried with BigDecimal.valueOf()

val1BD = BigDecimal.valueOf(val1);
val2BD = BigDecimal.valueOf(val2);

System.out.println(val1BD.subtract(val2BD));

And finally I got the output as 0.9.

My question is what is the difference between case 2 & case 3?

In case 2 why I got the output like that?


回答1:


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



回答2:


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);


来源:https://stackoverflow.com/questions/32546553/bigdecimal-subtraction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!