java math library for BigDecimal which allows null values

djmj picture djmj · Feb 12, 2013 · Viewed 89.4k times · Source

Is there a BigDecimal library with the basic operations of BigDecimal which allows null values?

Null should be treated as 0 for mathematical purpose.

I don't want to do all the null checks for possible null values.

You either never allow null values in database, application or view and initialize everything with new BigDecimal(0) or perform null checks on every usage for nullable values.

Something like:

public static BigDecimal add(final BigDecimal value, final BigDecimal augend)
{
    if (value == null)
        return augend;
    else if (augend == null)
        return value;
    else
        return value.add(augend);
}

public static BigDecimal multiply(final BigDecimal value, final BigDecimal multiplicand)
{
    if (value == null || multiplicand == null)
        return null;

    return value.multiply(multiplicand);
}

Answer

user207421 picture user207421 · Feb 12, 2013

Save the coding, just don't allow null values in the database. Make the default value zero.

As for new BigDecimal(0): no, use BigDecimal.ZERO.