Search code examples
javacollectionsbigdecimal

BigDecimal to allows null values


Looking for BigDecimal library which allows null values in BigDecimal?

Null should NOT be treated as 0 for mathematical purpose.

public abc{
  private BigDecimal amount;
   getter();
   setter();...
}
Class main{
if(tempStr == null) {                   
    abc.setAmt(new BigDecimal(" "));
}else if (tempStr != null && !tempStr.equals(" ")) {
      abc.setAmt(new BigDecimal(tempStr));  
}}

Amount should allow null values or Blank. Amount should also accept zero and other numbers.

I am getting amt as zero instead of null or blank


Solution

  • In Java null is used to represent undefined values. In your example, this would look as follows:

    if(tempStr == null) {                   
        abc.setAmt(null);
    } ...
    

    If you want to check if the string is not empty, you can look at some utililes like Apache Commons StringUtils:

    if(StringUtils.isBlank(tempStr)) {                   
        abc.setAmt(null);
    } ...
    

    If you want to avoid explicit null values, you may want to consider Optional<BigDecimal>. But it is a matter of taste.