Advertisement
Advertisement


Compare if BigDecimal is greater than zero


Question

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

2013/12/10
1
250
12/10/2013 4:56:16 PM

Accepted Answer

It's as simple as:

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

The documentation for compareTo actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.

2010/11/12
409
11/12/2010 12:21:14 PM


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

2013/07/05

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.

2020/06/05

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.

2018/04/22

 BigDecimal obj = new BigDecimal("100");
 if(obj.intValue()>0)
    System.out.println("yes");
2018/02/16

Source: https://stackoverflow.com/questions/4164521
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]