java

Compare BigDecimal values in Java


I want to compare values and execute some condition if some of the values are found. In Java I tried using this code:

if(item.getLenght().compareTo(BigDecimal.valueOf(50))
                        || item.getSocre().compareTo(BigDecimal.valueOf(500))
                        || item.getAge().compareTo(BigDecimal.valueOf(5000)))
                        {
                        ....... do some action
}

But I get error Operator '||' cannot be applied to 'int', 'int'

What is the proper way to implement this check?


Solution

  • The method BigDecimal#compareTo(BigDecimal) returns int, not boolean, so the operator || won't work.

    You need to change your code a bit:

    if (item.getLenght().compareTo(BigDecimal.valueOf(50)) == 0
        || item.getSocre().compareTo(BigDecimal.valueOf(500)) == 0
        || item.getAge().compareTo(BigDecimal.valueOf(5000)) == 0) {
    
        // do something funny
    }