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

后端 未结 11 614
灰色年华
灰色年华 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条回答
  •  猫巷女王i
    2020-12-04 07:01

    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().

提交回复
热议问题