BigDecimal 字段环比计算:以 2022 年为例
假设有一个 BigDecimal 类型的字段为'amount',表示某一年某个月的数值。
首先,需要查询出 2021 年和 2022 年 1 到 12 月的数据。然后,使用 BigDecimal 类的 subtract 方法来计算环比,即当前月份的值减去上一个月份的值,再除以上一个月份的值,最后乘以 100% 即可。
具体代码如下:
// 查询 2021 年和 2022 年 1 到 12 月的数据
List<BigDecimal> amounts = new ArrayList<>();
for (int i = 1; i <= 12; i++) {
// 查询 2021 年的数据
BigDecimal amount2021 = dao.getAmountByYearAndMonth(2021, i);
amounts.add(amount2021);
// 查询 2022 年的数据
BigDecimal amount2022 = dao.getAmountByYearAndMonth(2022, i);
amounts.add(amount2022);
// 计算环比
if (i > 1) {
BigDecimal currentMonthAmount = amounts.get(i * 2 - 1);
BigDecimal lastMonthAmount = amounts.get(i * 2 - 2);
BigDecimal ratio = currentMonthAmount.subtract(lastMonthAmount)
.divide(lastMonthAmount, 4, RoundingMode.HALF_UP)
.multiply(BigDecimal.valueOf(100));
System.out.println("2022 年 " + i + " 月的环比为:" + ratio + "%");
}
}
上述代码中,使用了一个 List 来存储查询出来的数据,其中索引为奇数的位置表示 2022 年的数据,索引为偶数的位置表示 2021 年的数据。在计算环比时,需要注意月份大于 1 的情况,因为第一个月的环比是不存在的。另外,使用了 BigDecimal 类的 divide 方法来进行除法运算,并指定了小数位数和舍入方式。
原文地址: https://www.cveoy.top/t/topic/mQaN 著作权归作者所有。请勿转载和采集!