1

I have a BigDecimal object, which I am checking for its value (greater or smaller than 100).

public static void main(String[] args) {    
    BigDecimal obj = new BigDecimal("100.3");   
    if (obj.intValue() > 100)
    {
        System.out.println("Greater than 100");
    }
    else
    {
        System.out.println("Not greater than 100");
    }   
}

But it's showing:

Not greater than 100

jAC
  • 5,195
  • 6
  • 40
  • 55
Pawan
  • 31,545
  • 102
  • 256
  • 434

1 Answers1

1

The reason your logic fails is that new BigDecimal("100.3").intValue() will (as the method name suggests) give you the value without decimal precision, i.e. 100. And 100 > 100 will be false.

Instead, use compareTo() method of BigDecimal to compare

BigDecimal oneHundred = new BigDecimal("100");
BigDecimal obj = new BigDecimal("100.3");
if (obj.compareTo(oneHundred) > 0) {
    System.out.println("Greader than");
}
Malte Hartwig
  • 4,477
  • 2
  • 14
  • 30
Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41