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); }
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.
If your main goal is validating BigDecimal dataType for nulls, then just make a comparison; yourBigDecimal != null. The above statement is enough for comparison and checking.
for this BigDecimal how do I set a empty value. Setting this value is a must. objName. setNetWeight(new BigDecimal("" or null or " ")) all results in NumberFormatException.
If you are using type BigDecimal, then its default value is null (it is object, not primitive type), so you get [1] automatically.
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
.
I had a similar problem (not related to a database though, just needed to sum up a couple of nullable BigDecimal
s). Did not find any library, so had to write the following function myself:
public static BigDecimal add(BigDecimal... addends) { BigDecimal sum = BigDecimal.ZERO; if (addends != null) { for (BigDecimal addend : addends) { if (addend == null) { addend = BigDecimal.ZERO; } sum = sum.add(addend); } } return sum; }
The same in Java 8:
public static BigDecimal add(BigDecimal... addends) { if (addends == null) { return BigDecimal.ZERO; } return Arrays.stream(addends) .filter(Objects::nonNull) .reduce(BigDecimal.ZERO, BigDecimal::add); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With