Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java math library for BigDecimal which allows null values

Tags:

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); } 
like image 750
djmj Avatar asked Feb 12 '13 00:02

djmj


People also ask

Can BigDecimal be null in Java?

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.

How do you do null check for BigDecimal in Java?

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.

How do I set empty value in BigDecimal?

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.

What is the default value for BigDecimal?

If you are using type BigDecimal, then its default value is null (it is object, not primitive type), so you get [1] automatically.


2 Answers

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.

like image 121
user207421 Avatar answered Nov 03 '22 00:11

user207421


I had a similar problem (not related to a database though, just needed to sum up a couple of nullable BigDecimals). 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); } 
like image 20
Bunarro Avatar answered Nov 02 '22 23:11

Bunarro