Search code examples
javabigdecimal

Check if BigDecimal value is in range


I have BiGDecimal price and i need to check if it is in some range. For example should be 3 conditions:

if (price >= 0 and price <=500) {
   ....
} else if (price >=500 && price <=1000) {
   ....
} else if (price > 1000) {
   ....
}

How to do it right using BigDecimal type.


Solution

  • That is achievable using the .compareTo() method. For instance:

    if ( price.compareTo( BigDecimal.valueOf( 500 ) > 0 
         && price.compareTo( BigDecimal.valueOf( 1000 ) < 0 ) {
        // price is larger than 500 and less than 1000
        ...
    }
    

    Quoting (and paraphrasing) from the JavaDoc:

    The suggested idiom for performing these comparisons is: (x.compareTo(y) op 0), where op is one of the six comparison operators [(<, ==, >, >=, !=, <=)]

    Cheers,