Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you check if a BigDecimal is equal to zero?

Using the compareTo Method Two BigDecimal objects that are equal in value but have a different scale (like 2.0 and 2.00) are considered equal by this method. Therefore, we can check BigDecimal. ZERO. compareTo(givenBdNumber) == 0 to decide if givenBdNumber has the value zero.

How do I check if BigDecimal is integer?

Depending on the source/usage of your BigDecimal values it might be faster to check if the scale <= 0 first. If it is, then it's definitely an integer value in the mathematical sense. If it is >0, then it could still be an integer value and the more expensive test would be needed.


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

Alternatively, signum() can be used:

if (price.signum() == 0) {
    return true;
}

There is a constant that you can check against:

someBigDecimal.compareTo(BigDecimal.ZERO) == 0

Alternatively, I think it is worth mentioning that the behavior of equals and compareTo methods in the class BigDecimal are not consistent with each other.

This basically means that:

BigDecimal someValue = new BigDecimal("0.00");
System.out.println(someValue.compareTo(BigDecimal.ZERO) == 0); // true
System.out.println(someValue.equals(BigDecimal.ZERO)); // false

Therefore, you have to be very careful with the scale in your someValue variable, otherwise you would get unexpected results.


I usually use the following:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0) { ... }

You would want to use equals() since they are objects, and utilize the built in ZERO instance:

if (selectPrice.equals(BigDecimal.ZERO))

Note that .equals() takes scale into account, so unless selectPrice is the same scale (0) as .ZERO then this will return false.

To take scale out of the equation as it were:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0)

I should note that for certain mathematical situations, 0.00 != 0, which is why I imagine .equals() takes the scale into account. 0.00 gives precision to the hundredths place, whereas 0 is not that precise. Depending on the situation you may want to stick with .equals().