Search code examples
javabigdecimal

Why doesn't my operation work when I use BigDecimal?


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.


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