Compare if BigDecimal is greater than zero

后端 未结 7 2018
既然无缘
既然无缘 2020-12-22 21:23

How can I compare if BigDecimal value is greater than zero?

相关标签:
7条回答
  • 2020-12-22 21:57

    it is safer to use the method compareTo()

        BigDecimal a = new BigDecimal(10);
        BigDecimal b = BigDecimal.ZERO;
    
        System.out.println(" result ==> " + a.compareTo(b));
    

    console print

        result ==> 1
    

    compareTo() returns

    • 1 if a is greater than b
    • -1 if b is less than b
    • 0 if a is equal to b

    now for your problem you can use

    if (value.compareTo(BigDecimal.ZERO) > 0)
    

    or

    if (value.compareTo(new BigDecimal(0)) > 0)
    

    I hope it helped you.

    0 讨论(0)
  • 2020-12-22 21:57
     BigDecimal obj = new BigDecimal("100");
     if(obj.intValue()>0)
        System.out.println("yes");
    
    0 讨论(0)
  • 2020-12-22 22:00

    Use compareTo() function that's built into the class.

    0 讨论(0)
  • 2020-12-22 22:02

    This works too:

    value > BigDecimal.ZERO

    0 讨论(0)
  • 2020-12-22 22:06

    Possible better way:

    if (value.signum() > 0)
    

    signum returns -1, 0, or 1 as the value of this BigDecimal is negative, zero, or positive.

    0 讨论(0)
  • 2020-12-22 22:10

    using ".intValue()" on BigDecimal object is not right when you want to check if its grater than zero. The only option left is ".compareTo()" method.

    0 讨论(0)
提交回复
热议问题