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

后端 未结 11 520
灰色年华
灰色年华 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 07:01
    BigDecimal.ZERO.setScale(2).equals(new BigDecimal("0.00"));
    
    0 讨论(0)
  • 2020-12-04 07:09

    Use compareTo(BigDecimal.ZERO) instead of equals():

    if (price.compareTo(BigDecimal.ZERO) == 0) // see below
    

    Comparing with the BigDecimal constant BigDecimal.ZERO avoids having to construct a new BigDecimal(0) every execution.

    FYI, BigDecimal also has constants BigDecimal.ONE and BigDecimal.TEN for your convenience.


    Note!

    The reason you can't use BigDecimal#equals() is that it takes scale into consideration:

    new BigDecimal("0").equals(BigDecimal.ZERO) // true
    new BigDecimal("0.00").equals(BigDecimal.ZERO) // false!
    

    so it's unsuitable for a purely numeric comparison. However, BigDecimal.compareTo() doesn't consider scale when comparing:

    new BigDecimal("0").compareTo(BigDecimal.ZERO) == 0 // true
    new BigDecimal("0.00").compareTo(BigDecimal.ZERO) == 0 // true
    
    0 讨论(0)
  • 2020-12-04 07:09

    Alternatively, signum() can be used:

    if (price.signum() == 0) {
        return true;
    }
    
    0 讨论(0)
  • 2020-12-04 07:10

    Just want to share here some helpful extensions for kotlin

    fun BigDecimal.isZero() = compareTo(BigDecimal.ZERO) == 0
    fun BigDecimal.isOne() = compareTo(BigDecimal.ONE) == 0
    fun BigDecimal.isTen() = compareTo(BigDecimal.TEN) == 0
    
    0 讨论(0)
  • 2020-12-04 07:18

    There is a constant that you can check against:

    someBigDecimal.compareTo(BigDecimal.ZERO) == 0
    
    0 讨论(0)
提交回复
热议问题