5

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;
JoJo
  • 4,643
  • 9
  • 42
  • 65
  • For the record, you can do a simple `return selectPriceList.contains(zeroDollarValue);`, or, alternately, `return selectPriceList.contains(new BigDecimal("0.0000");`. – SimplyPanda Jun 12 '12 at 14:23
  • 1
    Well... _does_ your list contain `BigDecimal.ZERO`? – Tharwen Jun 12 '12 at 14:28
  • http://stackoverflow.com/questions/3866514/why-bigdecimal5-50-not-equals-to-bigdecimal5-5-and-how-to-work-around-th – aglassman Jun 12 '12 at 14:32

1 Answers1

9

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.

Michael
  • 1,239
  • 9
  • 14