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.
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
}
In some contexts, you could use equals
rather than compareTo
to avoid a specific null check:
BigDecimal x = ...
if (BigDecimal.ZERO.equals(x)) { // "Yoda" condition.
// it is zero
} else {
// it is not zero
}
This relies on the Object.equals(Object)
javadoc which says that a.equals(null)
should return false
if a
is not null
.