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'm trying to:

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

But it always returns false.

This seems to work, but is a fix needed?

  BigDecimal zeroDollarValue = new BigDecimal("0.0000"); if (selectPriceList.contains(zeroDollarValue)) { return true; } return false; 
+4
source share
1 answer

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

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

Perhaps you can use

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

Assuming all your prices go up to four decimal places. If not, you may need to use

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

See the documentation for more information.

+9
source

All Articles