Compare if BigDecimal is greater than zero

JavaCompareBigdecimal

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

Possible better way:

if (value.signum() > 0)

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

Solution 3 - Java

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

Solution 4 - Java

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

Solution 5 - Java

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.

Solution 6 - Java

This works in Kotlin:

value > BigDecimal.ZERO

Solution 7 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSanthoshView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaAnton BessonovView Answer on Stackoverflow
Solution 3 - JavaduffymoView Answer on Stackoverflow
Solution 4 - JavayOshiView Answer on Stackoverflow
Solution 5 - JavaSatya MView Answer on Stackoverflow
Solution 6 - JavaRonaldPaguayView Answer on Stackoverflow
Solution 7 - JavaRama KrishnaView Answer on Stackoverflow