Skip to content

Check if BigDecimal variable is zero in Java (BigDecimal == 0)

From the Javadocs, A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. The value of the number represented by the BigDecimal is therefore (unscaledValue × 10-scale). Hence, BigDecimal isn’t a suitable for just numeric comparison. The reason you can’t use BigDecimal#equals() is that it takes scale into consideration:

Advertisements

To compare a BigDecimal variable with zero, try the following code snippets.

Method 1 : Using compareTo method

if (orderPrice.compareTo(BigDecimal.ZERO) == 0)
Advertisements

Method 1 : Using signum method

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.