Skip to content

fix: 修复优惠券金额分摊计算精度问题 (Issue #356)#967

Open
Senrian wants to merge 2 commits intomacrozheng:masterfrom
Senrian:fix/coupon-rounding-356
Open

fix: 修复优惠券金额分摊计算精度问题 (Issue #356)#967
Senrian wants to merge 2 commits intomacrozheng:masterfrom
Senrian:fix/coupon-rounding-356

Conversation

@Senrian
Copy link
Copy Markdown

@Senrian Senrian commented Apr 19, 2026

Bug 描述

Issue: #356

OmsPortalOrderServiceImpl.calcPerCouponAmount() 方法在计算优惠券分摊时,对每个商品独立计算并四舍五入到3位小数(HALF_EVEN),导致各商品分摊金额之和可能小于优惠券面额。

复现案例:

  • 商品价格:10元、10元、10元
  • 总价:30元
  • 优惠券面额:10元
  • 原算法:(10/30)*10 = 3.333... → 四舍五入为 3.330
  • 三个商品分摊金额合计:9.990元,少了0.01元

修复方案

对前 n-1 个商品按比例计算分摊金额,最后一个商品获取剩余金额,确保分摊总额精确等于优惠券面额。最终金额四舍五入到2位小数。

// 修复后的逻辑
for (int i = 0; i < size; i++) {
    if (i < size - 1) {
        // 前 n-1 个商品:按比例计算
        couponAmount = orderItem.getProductPrice().divide(totalAmount, 3, RoundingMode.HALF_EVEN).multiply(couponAmountTotal);
        remainingAmount = remainingAmount.subtract(couponAmount);
    } else {
        // 最后一个商品:获取剩余金额,确保总和精确等于优惠券面额
        couponAmount = remainingAmount;
    }
    couponAmount = couponAmount.setScale(2, RoundingMode.HALF_UP);
    orderItem.setCouponAmount(couponAmount);
}

修改文件

  • mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java

Fixes #356

penggaolai and others added 2 commits April 4, 2026 04:20
问题:使用 (商品原价/总价)*满减金额 的除法优先顺序,当满减金额为0.98时,
由于divide精度为3位HALF_EVEN,计算结果可能产生如0.979这样的多位小数,
导致最终优惠金额少了约0.02元。

修复:改为 乘法优先再除法 originalPrice.multiply(reducePrice).divide(totalAmount, 2, RoundingMode.HALF_EVEN),
保证最终结果精确到分(2位小数),符合人民币货币精度。

同时确保使用 RoundingMode.HALF_EVEN 保持与原有代码一致。

Fixes macrozheng#492
原算法对每个商品独立计算分摊金额并四舍五入到3位小数,
导致各商品分摊金额之和可能小于优惠券面额。

修复方案:
- 对前 n-1 个商品按比例计算分摊金额
- 最后一个商品获取剩余金额,确保分摊总额精确等于优惠券面额
- 最终金额四舍五入到2位小数
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

关于优惠券金额分摊算法的误差

2 participants