简体   繁体   English

BigDecimal 除法抛出 ArithmeticException:除以零,即使我检查它

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

Hey guys I'm currently working with talend and have to calculate some KPI's.嘿伙计们,我目前正在与 talend 合作,并且必须计算一些 KPI。

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.即使我在不同的计算中遵循相同的模式并且它们可以正常工作,我现在每次都得到ArithmeticException: Division by zero

(((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.) functions_pattern.checkIfNullnull值设置为零(在本例中为BigDecimal.ZERO )我还尝试了各种变化(单独null检查等)

Also since I'm working with talend I have to use ternary operators.另外,由于我正在使用 talend,因此我必须使用三元运算符。

Using == to test a BigDecimal is a bad idea.使用==来测试BigDecimal是个坏主意。

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 .即使假设checkIfNullnull时返回Decimal.ZERO ,您仍然会rechnung1.netto可能是零的问题,即!= 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. equals还有一个问题,即两个BigDecimal值的值和比例必须相等才能被视为相等。

This is the safe way to test a (non-null) BigDecimal value for zero:这是测试(非空) BigDecimal值为零的安全方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM