无尾差按比例分摊金额算法

public void batchAssignSettlement(BuySettleVo vo) {
        //查询账单下所有一级国内运费费用明细
        List settlementCostList = settlementCostModelObjectFactory.select().eq("settlement", vo.getSettlementId()).eq("settleCostItem.name", "国内运费").isNull("uc_settlement_cost").findAll();
        if (ObjectUtil.isNotEmpty(settlementCostList)) {
            //总含税金额
            BigDecimal allTotalAmount = settlementCostList.stream().map(SettlementCost::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            //已分配的金额
            BigDecimal assignedAmount = BigDecimal.ZERO;
            //输入的要分配的含税金额
            BigDecimal needAssignedAmount = vo.getTotalAmount();
            for (int i = 0; i < settlementCostList.size(); i++) {
                SettlementCost settlementCost = settlementCostList.get(i);
                if (i == settlementCostList.size() - 1 && i != 0) {
                    //最后一条减法避免尾差
                    vo.setTotalAmount(needAssignedAmount.subtract(assignedAmount));
                } else {
                    //按比例分摊
                    BigDecimal assignAmount = needAssignedAmount.multiply(settlementCost.getTotalAmount()).divide(allTotalAmount, 2, RoundingMode.HALF_UP);
                    vo.setTotalAmount(assignAmount);
                    assignedAmount = assignedAmount.add(assignAmount);
                }
                assignSettlement(settlementCost, vo);
            }
        } else {
            throw bizMessage.error("该账单无结算费用:国内运费");
        }
    }

你可能感兴趣的:(java,算法,java,比例分摊,尾差)