CKTIS / Java
BigDecimal.ZERO — comparing a discount amount with zero
Use `BigDecimal.ZERO` with `compareTo` to check whether a discount amount is numerically zero, regardless of its scale.
Version: Java SE 21
Syntax
import java.math.BigDecimal;
// Inside a method, with discount already declared as a BigDecimal:
boolean noDiscount = discount.compareTo(BigDecimal.ZERO) == 0;BigDecimal.ZERO is a public static final field of java.math.BigDecimal. It provides the immutable decimal value zero with scale 0. To use the short class name BigDecimal, add import java.math.BigDecimal;.
To check whether a discount amount named discount is zero, use discount.compareTo(BigDecimal.ZERO) == 0. The compareTo method compares numerical values regardless of scale. It returns -1, 0, or 1 when the amount is less than, equal to, or greater than zero, respectively.
new BigDecimal("0.00") has scale 2: it is numerically zero, but discount.equals(BigDecimal.ZERO) returns false for this amount because equals requires both the value and the scale to match. Do not use discount == BigDecimal.ZERO to compare amounts: there, == checks whether both references point to the same object. In the recommended expression, == compares the int result with zero.
Examples
import java.math.BigDecimal;
public class DiscountCheck {
public static void main(String[] args) {
BigDecimal discount = new BigDecimal("0.00");
boolean noDiscount = discount.compareTo(BigDecimal.ZERO) == 0;
System.out.println("No discount: " + noDiscount);
System.out.println("Same value and scale: " + discount.equals(BigDecimal.ZERO));
}
}Result
No discount: true Same value and scale: false
The first line confirms that an amount of `0.00` means there is no discount. The second shows that the scales differ even though the numerical values match.
Related lessons
- Java · Lesson 69 · Basic · Version: 2