How to check if BigDecimal variable == 0 in java?

JoJo picture JoJo · Jun 8, 2012 · Viewed 256.1k times · Source

I have the following code in Java;

BigDecimal price; // assigned elsewhere

if (price.compareTo(new BigDecimal("0.00")) == 0) {
    return true;
}

What is the best way to write the if condition?

Answer

Bohemian picture Bohemian · Jun 8, 2012

Use compareTo(BigDecimal.ZERO) instead of equals():

if (price.compareTo(BigDecimal.ZERO) == 0) // see below

Comparing with the BigDecimal constant BigDecimal.ZERO avoids having to construct a new BigDecimal(0) every execution.

FYI, BigDecimal also has constants BigDecimal.ONE and BigDecimal.TEN for your convenience.


Note!

The reason you can't use BigDecimal#equals() is that it takes scale into consideration:

new BigDecimal("0").equals(BigDecimal.ZERO) // true
new BigDecimal("0.00").equals(BigDecimal.ZERO) // false!

so it's unsuitable for a purely numeric comparison. However, BigDecimal.compareTo() doesn't consider scale when comparing:

new BigDecimal("0").compareTo(BigDecimal.ZERO) == 0 // true
new BigDecimal("0.00").compareTo(BigDecimal.ZERO) == 0 // true