java.lang.ArithmeticException:非终止十进制扩展

时间:2015-07-31 03:39:45

标签: java

if (builderAggregateCalculationsType == AggregateCalculationsType.AGGREGATE_AVERAGE) {
            BigDecimal quarterDivisor = new BigDecimal(3);
            quarterDivisor = quarterDivisor.setScale(
                    aggregateCalculationsNumberOfDecimalPlaces,
                    RoundingMode.HALF_UP);
            firstQuarterSum = firstQuarterSum.setScale(
                    aggregateCalculationsNumberOfDecimalPlaces,
                    RoundingMode.HALF_UP);
            secondQuarterSum = secondQuarterSum.setScale(
                    aggregateCalculationsNumberOfDecimalPlaces,
                    RoundingMode.HALF_UP);

            firstQuarterSum = firstQuarterSum.divide(quarterDivisor);
            secondQuarterSum = secondQuarterSum.divide(quarterDivisor);

        }

1 个答案:

答案 0 :(得分:3)

问题是因为除法结果产生Non-terminating分数。像1/3这样的内容会生成0.3333....,但不会终止。

如果您允许某些错误,可以指定RoundingMode并使用它,

firstQuarterSum.divide(quarterDivisor, RoundingMode.HALF_UP); // Or any other rounding mode you prefer.