JoJo JoJo - 1 year ago 213
Java Question

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

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 Source

Use the BigDecimal constant BigDecimal.ZERO:

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

This avoids constructing a new BigDecimal for zero every call.

FYI, BigDecimal has constants BigDecimal.ONE and BigDecimal.TEN too.


The method BigDecimal.equals() takes scale into consideration:

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

so it's unsuitable for this kind of 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download