四舍五入 BigDecimal 除法流结果时的 IntelliJ 提示

IntelliJ hint while rounding BigDecimal division stream result

在流操作结束时划分结果时,IntelliJ 提示出现了一些奇怪的问题。

products.stream()
        .filter(
            order ->
                order.getEstimatedRealizationDate().compareTo(begin) > 0
                    && order.getEstimatedRealizationDate().compareTo(end) < 0)
        .map(order -> order.getProduct().getPrice())
        .reduce(ZERO, BigDecimal::add)
        .divide(valueOf(productList.size()))
        .setScale(3, RoundingMode.CEILING);

无论您如何设置舍入,IntelliJ 不断声称除法运算可能会以消息和背光除法运算的形式出现 ArtithmeticException 的形式存在风险。我正在使用 round() 选项。

Reports calls to divide() or setScale() without a rounding mode argument. Such calls can lead to an ArithmeticException when the exact value cannot be represented in the result (e.g. because it has a non-terminating decimal expansion). Specifying a rounding mode prevents the ArithmeticException.

我的印象是我已经尝试了所有可能的变体,但 IntelliJ 仍然没有放弃。请建议我做错了什么。提前感谢各种帮助。

setScale 只是 returns 具有指定比例的 BigDecimal 对象。您想使用重载 divide 方法

divide(BigDecimal divisor, int scale, RoundingMode roundingMode):

products.stream()
        .filter(
            order ->
                order.getEstimatedRealizationDate().compareTo(begin) > 0
                    && order.getEstimatedRealizationDate().compareTo(end) < 0)
        .map(order -> order.getProduct().getPrice())
        .reduce(ZERO, BigDecimal::add)
        .divide(valueOf(productList.size()), 3, RoundingMode.CEILING);

在此示例中,我使用 RoundingMode.CEILING,但如果您想使用不同的舍入模式,这里是 RoundingMode 的文档。