Why does my work not work when I use BigDecimal?

I am trying to perform an operation using BigDecimal , but always returns 0 . Why does it work when I use double ?

 public static void main(String[] args) { double a = 3376.88; BigDecimal b = new BigDecimal(a); System.out.println(aa/1.05); System.out.println(b.subtract(b).divide(new BigDecimal(1.05)).doubleValue()); } 

Thanks.

+6
source share
2 answers

You do not perform the same operations.

When you do double operations, the normal order of java operations is applied:

 aa/1.05 = a - (a/1.05) 

But when you execute methods on BigDecimal , operations are evaluated in the order in which you call them, therefore

 b.subtract(b).divide(new BigDecimal(1.05)) 

equivalently

 (b - b) / 1.05 = 0 / 1.05 = 0 
+8
source

When you call method calls for BigDecimal , the order of operations is not preserved, as in mathematics, and as with double operators in Java. Methods will be executed in order. This means that b.subtract(b) is executed first, which results in BigDecimal 0 .

To get an equivalent result, follow the order of operations by sending the result of the divide method to the subtract method.

 System.out.println(b.subtract( b.divide(new BigDecimal(1.05)) ).doubleValue()); 
+8
source

All Articles