假设有两个 BigDecimal 类型的字段:total1 表示 2021 年的总数,total2 表示 2022 年的总数。可以使用以下代码计算出 2022 年 1 到 12 月每个月的环比:

BigDecimal[] monthlyRatios = new BigDecimal[12];
BigDecimal lastMonthTotal = total1;
for (int i = 0; i < 12; i++) {
    BigDecimal currentMonthTotal = ...; // 计算当前月份的总数
    BigDecimal monthlyRatio = currentMonthTotal.subtract(lastMonthTotal)
            .divide(lastMonthTotal, 4, RoundingMode.HALF_UP);
    monthlyRatios[i] = monthlyRatio;
    lastMonthTotal = currentMonthTotal;
}

其中,monthlyRatios 数组存储了每个月的环比值,lastMonthTotal 表示上一个月的总数,currentMonthTotal 表示当前月份的总数。在计算每个月的环比时,先用当前月份的总数减去上一个月的总数,再除以上一个月的总数,保留四位小数,并使用四舍五入的方式。最后将计算出的环比值存储到 monthlyRatios 数组中即可。

Java BigDecimal: 如何计算2022年每月环比 (含1月份)

原文地址: https://www.cveoy.top/t/topic/mRyw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录