Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BigDecimal Subtraction

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?

like image 635
Rakesh KR Avatar asked Sep 13 '15 05:09

Rakesh KR


2 Answers

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);
like image 168
SLuck Avatar answered Sep 18 '22 17:09

SLuck


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
like image 36
akash Avatar answered Sep 17 '22 17:09

akash