Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use .contains(BigDecimal.ZERO) when reading a list in JAVA?

Can we use .contains(BigDecimal.ZERO) when reading a list in JAVA ??

I am trying:

    if (selectPriceList.contains(BigDecimal.ZERO)) {
        return true;
    }
    return false;

But it always returns false.

This seems to work but does it need correction?

    BigDecimal zeroDollarValue = new BigDecimal("0.0000");
    if (selectPriceList.contains(zeroDollarValue)) {
        return true;
    }
    return false;
like image 265
JoJo Avatar asked Jun 12 '12 14:06

JoJo


1 Answers

The problem occurs because the scale, the number of digits to the right of the decimal point, of BigDecimal.ZERO is set to 0, while the scale of zeroDollarValue is 4.

The equals method of BigDecimal compares both the scale and the value - if either are different, it returns false.

You can probably use

return selectPriceList.contains(BigDecimal.ZERO.setScale(4));

Assuming that all of your prices go out to four decimal places. If not, you might have to use

for(BigDecimal bd : selectPriceList) {
    if(bd.compareTo(BigDecimal.ZERO) == 0) {
        return true;
    }
}
return false;

For more information, see the documentation.

like image 83
Michael Avatar answered Sep 30 '22 03:09

Michael