Question

I'm trying to do an operation using BigDecimal but it always return 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(a-a/1.05);
    System.out.println(b.subtract(b).divide(new BigDecimal(1.05)).doubleValue());
}

Thanks.

Était-ce utile?

La solution

You are not performing the same operations.

When you are doing the double operations, the normal java order of operations is applying:

a-a/1.05  
= a - (a/1.05)

But when you are running the methods on BigDecimal, the operations are evaluated in the order you are calling them, so

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

is equivalent to

(b - b) / 1.05
= 0 / 1.05
= 0

Autres conseils

When you chain method calls for BigDecimal, the order of operations is not preserved as it is in math, and as with double operators in Java. The methods will be executed in order. That means that b.subtract(b) happens first, resulting in the BigDecimal 0.

To obtain the equivalent result, enforce the order of operations yourself by sending the result of the divide method to the subtract method.

System.out.println(b.subtract( b.divide(new BigDecimal(1.05)) ).doubleValue());
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top