BigDecimal division throwing ArithmeticException: Division by zero even when i check against it

2k Views Asked by At

Hey guys I'm currently working with talend and have to calculate some KPI's.

I'm getting the ArithmeticException: Division by zero every time now even if I follow the same schema in different calculations and they work without problems.

(((functions_pattern.checkIfNull(opportunities1.tatsaechlicherumsatz)) == 
BigDecimal.ZERO) || ((functions_pattern.checkIfNull(rechnung1.netto)) == 
BigDecimal.ZERO))
 ?  BigDecimal.ZERO  
 : (rechnung1.netto.divide(opportunities1.tatsaechlicherumsatz , 
    java.math.MathContext.DECIMAL32))

functions_pattern.checkIfNull sets a null value to zero (in this case BigDecimal.ZERO) I also tried various variations on this (separate null checking etc.)

Also since I'm working with talend I have to use ternary operators.

1

There are 1 best solutions below

0
Stephen C On BEST ANSWER

Using == to test a BigDecimal is a bad idea.

Even assuming that checkIfNull returns Decimal.ZERO when null, you still have the problem that rechnung1.netto could have been a zero that is != Decimal.ZERO.

Also equals has the problem that both the value and the scale must be equal for two BigDecimal values to be considered equal.

This is the safe way to test a (non-null) BigDecimal value for zero:

 BigDecimal x = ...
 if (x.compareTo(BigDecimal.ZERO) == 0) {
     // it is zero
 } else {
     // it is not zero
 }