Search code examples
javajava-8bigdecimal

Null Safe Compare two bigdecimal objects having 0.0 and 0


Initially code was :

            if(!Objects.equals(src.getApplicationItemCost(), dest.getApplicationItemCost())){
               log.info("Difference")
            }

Output:

      getApplicationItemCost: src:0.0| dest:0
      Difference

ApplicationItemCost is of type BigDecimal.

If I use compareTo then I have to explicitly check nulls like :

LOG.info("getApplicationItemCost: src:" + src.getApplicationItemCost() + "| dest:" + dest.getApplicationItemCost());
        if((src.getApplicationItemCost()==null && dest.getApplicationItemCost()!=null)
                || (src.getApplicationItemCost()!=null && dest.getApplicationItemCost()==null)
                || !Objects.equals(src.getApplicationItemCost(), dest.getApplicationItemCost())
                || src.getApplicationItemCost().compareTo(dest.getApplicationItemCost())!=0 )

Any suggestion to compare 0.0 and 0. Why is this difference? (May be database has Number field and when converted to big decimal it does not show 0.0?)


Solution

  • Build a comparator:

    Comparator<BigDecimal> c = Comparator.nullsFirst(Comparator.naturalOrder());
    

    (Or nullsLast, it doesn't matter if you're only ever comparing to zero).

    Then:

    if (c.compare(first, second) != 0) {
      // ...
    }