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

后端 未结 11 613
灰色年华
灰色年华 2020-12-04 06:29

I have the following code in Java;

BigDecimal price; // assigned elsewhere

if (price.compareTo(new BigDecimal(\"0.00\")) == 0) {
    return true;
}
<         


        
11条回答
  •  执念已碎
    2020-12-04 06:56

    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 result.

提交回复
热议问题