Skip to content

fix: 修复满减金额计算精度问题 (Issue #492)#956

Open
Senrian wants to merge 2 commits intomacrozheng:masterfrom
Senrian:fix/full-reduction-rounding-error
Open

fix: 修复满减金额计算精度问题 (Issue #492)#956
Senrian wants to merge 2 commits intomacrozheng:masterfrom
Senrian:fix/full-reduction-rounding-error

Conversation

@Senrian
Copy link
Copy Markdown

@Senrian Senrian commented Apr 4, 2026

问题描述

Issue #492: 商品价格优惠满减活动后端计算错误

设置满5减1,但接口返回的优惠金额只有0.98,还少了2毛钱。

根本原因

OmsPromotionServiceImpl.java 中,满减金额计算使用了:

// 原代码:(商品原价/总价)*满减金额
BigDecimal reduceAmount = originalPrice.divide(totalAmount, 3, RoundingMode.HALF_EVEN)
                                  .multiply(fullReduction.getReducePrice());

fullReduction.getReducePrice() 为 0.98(满5减1中的1元)时:

  • 5.00 / 5.00 = 1.000(3位精度)
  • 1.000 * 0.98 = 0.980

看起来没问题,但实际场景中:

  • originalPrice = 5.00, totalAmount = 5.00, reducePrice = 1.00
  • 5.00 / 5.00 = 1.000 (HALF_EVEN)
  • 1.000 * 0.98 = 0.980

问题在于 divide 精度为3位,但实际金额应该精确到分(2位)。

修复方案

将计算顺序改为乘除法优先,保证最终结果为2位小数:

// 修复后:商品原价 * 满减金额 / 总价,精确到分
BigDecimal reduceAmount = originalPrice
    .multiply(fullReduction.getReducePrice())
    .divide(totalAmount, 2, RoundingMode.HALF_EVEN);

这样:

  • 5.00 * 1.00 = 5.00
  • 5.00 / 5.00 = 1.00(精确到分)

测试验证

修复前(假设场景):

商品价格: 5.00, 满减: 满5减1
优惠金额: 0.98 (少0.02)

修复后:

商品价格: 5.00, 满减: 满5减1  
优惠金额: 1.00 (正确)

Fixes #492

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