How to compare if two BigDecimals are equal in Java?

In Java, when comparing two BigDecimal objects for equality, you should not directly use the == operator because this compares object references, not actual values. Instead, you should use the compareTo method.

Here is an example code comparing two BigDecimal objects for equality:

import java.math.BigDecimal;

public class BigDecimalComparisonExample {
    public static void main(String[] args) {
        BigDecimal num1 = new BigDecimal("10.0");
        BigDecimal num2 = new BigDecimal("10.00");

        if (num1.compareTo(num2) == 0) {
            System.out.println("num1 is equal to num2");
        } else {
            System.out.println("num1 is not equal to num2");
        }
    }
}

In the above example, we created two BigDecimal objects num1 and num2 and compared them using the compareTo method. A return value of 0 from the compareTo method indicates that the two BigDecimal objects are equal.

广告
Closing in 10 seconds
bannerAds