BigDecimal Subtraction

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

 double val1 = 2.0; double val2 = 1.10; System.out.println(val1 - val2); 

and I got the result as

 0.8999999999999999 

To get output 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 a conclusion like,

 0.899999999999999911182158029987476766109466552734375 

Then I tried using 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 and case 3?

In case 2, why did I get such a conclusion?

+6
source share
1 answer

BigDecimal.valueOf(double d) uses the canonical String representation of the double value, inside Double.toString(double) used that you get 0.9 in the second case.

Note. . This is usually the preferred way to convert a double (or float) to BigDecimal, since the return value is equal to the result of constructing BigDecimal from the result of using Double.toString(double) .

While new BigDecimal(0.9) , it will convert the value to the exact floating point representation of the double value without using the String representation.

Translates double to BigDecimal , which is the exact decimal representation of a binary binary floating-point value.

...

NOTES:

  • The results of this constructor may 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 
+6
source

All Articles