Search code examples
javabigdecimal

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?


Solution

  • 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