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,000
  • 6
  • 41
  • 52
Pawan
  • 29,827
  • 94
  • 242
  • 415

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,348
  • 2
  • 12
  • 30
Ashishkumar Singh
  • 3,452
  • 1
  • 21
  • 37