下单的过程中我们会根据配送方式的不同来计算相应的运费,并将每个商品分摊到的运费金额放到订单的items表里,如果按照相应的比例进行分摊,就会存在四舍五入的小数分摊不均,比如10元运费3件商品,每个就会分摊到3.33,这样就会有0.01的误差存在,为了避免这样的误差存在,我们会记录下前几次分摊到的金额值总和,最后一个用总运费金额减去之前的总和,这样减避免了误差的存在。订单发生退货的时候就会根据退货数量不同来决定退还给用户多少金额。逻辑代码如下,假设订单总运费100元,所有商品的价格均取两位小数
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
@Getter
@Setter
public class TestVo {
private BigDecimal a;
private BigDecimal b;
public TestVo(BigDecimal a, BigDecimal b) {
this.a = a;
this.b = b;
}
}
public static void main(String[] args) {
BigDecimal bigDecimal = new BigDecimal("1600");
List<TestVo> list = new ArrayList<>();
list.add(new TestVo(new BigDecimal(700), null));
list.add(new TestVo(new BigDecimal(400), null));
list.add(new TestVo(new BigDecimal(500), null));
saveReceivedAmount(bigDecimal, list);
System.out.println(JSON.toJSONString(list));
}
private static void saveReceivedAmount(BigDecimal amount, List<TestVo> list) {
AtomicReference<BigDecimal> atomicReceivedAmount = new AtomicReference<>();
if(amount != null){
atomicReceivedAmount.set(amount);
}
int len = list.size();
for (int i = 0; i < len; i++) {
TestVo vo = list.get(i);
if(amount != null ){
if(len >= 2){
BigDecimal decimal = atomicReceivedAmount.get();
if(decimal.compareTo(vo.getA()) <= 0){
vo.setB(decimal);
atomicReceivedAmount.set(new BigDecimal("0"));
}else {
if(i == len-1){
vo.setB(decimal);
}else{
vo.setB(vo.getA());
atomicReceivedAmount.set(decimal.subtract(vo.getA()));
}
}
}else{
//回款金额
vo.setB(amount);
}
}else{
vo.setB(null);
}
}
}
分摊
/**
* 按户数分摊方式
* 分摊计算采用截取小数精确位数后的小数值BigDecimal.ROUND_DOWN
* 目的:指定金额200元,平均分配给6户,分摊前后金额相等
*/
private static void hsFt() {
BigDecimal[] repair_shou_Amt = new BigDecimal[6];// 每个分户应承担维修金额
BigDecimal fact_repair_Amt = new BigDecimal("0");// 维修对象的实际费用(不含零头)
//待分摊金额
BigDecimal ft_amt = new BigDecimal("200");
//分户总数
int count = repair_shou_Amt.length;
for(int i = 0; i < count; i++) {
//求每个分户的承担金额=分摊金额/总户数
repair_shou_Amt[i] =ft_amt.divide(new BigDecimal(count), 2, BigDecimal.ROUND_DOWN); //截掉精度之后的小数位的值
//实际分摊承担总金额---小数点截取后的总金额
fact_repair_Amt = fact_repair_Amt.add(repair_shou_Amt[i]);
}
// 零头 = 分摊实际承担金额-待分摊金额
BigDecimal repair_oddment_amt = fact_repair_Amt.subtract(ft_amt);
// 算出要参与分摊零头的户数-截掉精度后的小数位的值累加后的每个值假设最大也只可能为0.00999999999999999999无限接近0.01
int repair_int = repair_oddment_amt.multiply(new BigDecimal("100")).abs().intValue();
// 把维修金额零头分摊到分户上,如果参与维修零头的户数大于零或者小于总户数,则进行分摊,否则报错
if( (repair_int < count) && (repair_int > 0) ) {
// 如果零头小于零,则说明有repair_int个分户承担的金额少一分钱0.01,需要加一分钱
if( repair_oddment_amt.compareTo(new BigDecimal("0")) < 0 ) {
for(int i = 0; i < repair_int; i++) {
repair_shou_Amt[i] = repair_shou_Amt[i].add(new BigDecimal("0.01"));
}
} else {
// 如果零头大于零,则说明有repair_int个分户承担的金额多一分钱0.01,需要减去一分钱
for(int i = 0; i < repair_int; i++) {
repair_shou_Amt[i] = repair_shou_Amt[i].subtract(new BigDecimal("0.01"));
}
}
} else if( repair_int == 0 ) {
// 零头如果为零,不需要处理
} else {
System.out.println("非法操作!");
}
//分摊金额
System.out.println(JSON.toJSONString(repair_shou_Amt));
}
- BigDecimal.add() 增加金额无效,需要赋值 bigDecimal = BigDecimal.add();
在调用方法事务中,尽量少用FeignClient,因为在事务内,查询数据可能,不是事务生效后的数据,所以要用Mapper或者Service服务。
错误示例:<br />
/**
* 查询订单的未支付金额
* @param salesHeadCode
* @param mallSalesContractCode
* @return
*/
public BigDecimal getNotPayAmt(String salesHeadCode, String mallSalesContractCode) {
log.info("查询订单的未支付金额入参salesHeadCode:{}, mallSalesContractCode:{}", salesHeadCode, mallSalesContractCode);
// 查询签收金额(应付金额)
BigDecimal shouldPayAmt = new BigDecimal(0);
BigDecimal paiedAmt = new BigDecimal(0);
List<String> salesHeadCodes = Arrays.asList(salesHeadCode);
ResponseBO<List<DeliveryOrderProductVO>> deliveryOrderProductVOs = deliveryOrderFeignClient.calReceiptedAmount(salesHeadCodes);
ResponseBO<List<com.vd.canary.obmp.transport.api.response.returnorder.ReturnOrderProductVO>> returnOrderProductVOs = returnOrderFeignClient.calReturnedAmount(salesHeadCodes);
if(ObjectUtil.isNotEmpty(deliveryOrderProductVOs) && CollectionUtil.isNotEmpty(deliveryOrderProductVOs.getData())){
DeliveryOrderProductVO deliveryOrderProductVO = deliveryOrderProductVOs.getData().get(0);
shouldPayAmt = deliveryOrderProductVO.getSalesTotalAmount();
}
if(ObjectUtil.isNotEmpty(returnOrderProductVOs) && CollectionUtil.isNotEmpty(returnOrderProductVOs.getData())){
com.vd.canary.obmp.transport.api.response.returnorder.ReturnOrderProductVO returnOrderProductVO = returnOrderProductVOs.getData().get(0);
shouldPayAmt = shouldPayAmt.subtract(returnOrderProductVO.getSalesReturnAmount());
}
ArmReceiptQueryPageReq armReceiptQueryPageReq = new ArmReceiptQueryPageReq();
armReceiptQueryPageReq.setSaleContractCode(mallSalesContractCode);
armReceiptQueryPageReq.setPageNum(1);
armReceiptQueryPageReq.setPageSize(200);
//TODO 在@Transactional事务中,不要调用本服务的FeignClient的方法,会导致查询数据不是最新的或者不是最新更新的
ResponseBO<ArmReceiptPageResp> armReceiptPageRespResponseBO = armReceiptHeadFeignClient.queryPageReceiptList(armReceiptQueryPageReq);
log.info("查询订单的支付信息申请结算已支付金额:{}, salesHeadCode:{}", JSON.toJSONString(armReceiptPageRespResponseBO), salesHeadCode);
List<String> onLinePaymentChannel = Arrays.asList("1", "5", "6", "7");
if(ObjectUtil.isNotEmpty(armReceiptPageRespResponseBO) && ObjectUtil.isNotEmpty(armReceiptPageRespResponseBO.getData()) && CollectionUtil.isNotEmpty(armReceiptPageRespResponseBO.getData().getList())){
List<ArmReceiptPageVO> list = armReceiptPageRespResponseBO.getData().getList();
List<ArmReceiptPageVO> voList = armReceiptPageRespResponseBO.getData().getList();
paiedAmt = list.stream().filter(ar -> "20".equals(ar.getAnnounceStatus())).map(ArmReceiptPageVO::getReceiptedAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("查询订单的未支付金额paiedAmt:{}, salesHeadCode:{}", paiedAmt, salesHeadCode);
// 需要加上未认领的,但是支付方式是企业网银,支付宝、微信的金额(在途金额)
BigDecimal onlinePayAmtB = voList.stream().filter(ar -> "10".equals(ar.getAnnounceStatus()) && onLinePaymentChannel.contains(ar.getPaymentChannel())).map(ArmReceiptPageVO::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("查询订单的未支付金额onlinePayAmt:{}, salesHeadCode:{}", onlinePayAmtB, salesHeadCode);
//TODO 此地方没有将金额赋值给 paiedAmt 导致存在问题
paiedAmt.add(onlinePayAmtB == null ? new BigDecimal(0) : onlinePayAmtB);
log.info("查询签收金额(应付金额):{}", paiedAmt);
}
BigDecimal notPayAmt = shouldPayAmt.subtract(paiedAmt);
log.info("查询订单的未支付金额出参shouldPayAmt:{}, paiedAmt:{}, notPayAmt:{}, salesHeadCode:{}", shouldPayAmt, paiedAmt, notPayAmt, salesHeadCode);
return notPayAmt;
}
正确示例:
/**
* 查询订单的未支付金额
* @param salesHeadCode
* @param mallSalesContractCode
* @return
*/
public BigDecimal getNotPayAmt(String salesHeadCode, String mallSalesContractCode) {
log.info("查询订单的未支付金额入参salesHeadCode:{}, mallSalesContractCode:{}", salesHeadCode, mallSalesContractCode);
// 查询签收金额(应付金额)
BigDecimal shouldPayAmt = new BigDecimal(0);
BigDecimal paiedAmt = new BigDecimal(0);
List<String> salesHeadCodes = Arrays.asList(salesHeadCode);
ResponseBO<List<DeliveryOrderProductVO>> deliveryOrderProductVOs = deliveryOrderFeignClient.calReceiptedAmount(salesHeadCodes);
ResponseBO<List<com.vd.canary.obmp.transport.api.response.returnorder.ReturnOrderProductVO>> returnOrderProductVOs = returnOrderFeignClient.calReturnedAmount(salesHeadCodes);
if(ObjectUtil.isNotEmpty(deliveryOrderProductVOs) && CollectionUtil.isNotEmpty(deliveryOrderProductVOs.getData())){
DeliveryOrderProductVO deliveryOrderProductVO = deliveryOrderProductVOs.getData().get(0);
shouldPayAmt = deliveryOrderProductVO.getSalesTotalAmount();
}
if(ObjectUtil.isNotEmpty(returnOrderProductVOs) && CollectionUtil.isNotEmpty(returnOrderProductVOs.getData())){
com.vd.canary.obmp.transport.api.response.returnorder.ReturnOrderProductVO returnOrderProductVO = returnOrderProductVOs.getData().get(0);
shouldPayAmt = shouldPayAmt.subtract(returnOrderProductVO.getSalesReturnAmount());
}
ArmReceiptQueryPageReq armReceiptQueryPageReq = new ArmReceiptQueryPageReq();
armReceiptQueryPageReq.setSaleContractCode(mallSalesContractCode);
armReceiptQueryPageReq.setPageNum(1);
armReceiptQueryPageReq.setPageSize(200);
ResponseBO<ArmReceiptPageResp> armReceiptPageRespResponseBO = armReceiptHeadService.queryPageReceiptList(armReceiptQueryPageReq);
log.info("查询订单的支付信息申请结算已支付金额:{}, salesHeadCode:{}", JSON.toJSONString(armReceiptPageRespResponseBO), salesHeadCode);
List<String> onLinePaymentChannel = Arrays.asList("1", "5", "6", "7");
if(ObjectUtil.isNotEmpty(armReceiptPageRespResponseBO) && ObjectUtil.isNotEmpty(armReceiptPageRespResponseBO.getData()) && CollectionUtil.isNotEmpty(armReceiptPageRespResponseBO.getData().getList())){
List<ArmReceiptPageVO> list = armReceiptPageRespResponseBO.getData().getList();
List<ArmReceiptPageVO> voList = armReceiptPageRespResponseBO.getData().getList();
paiedAmt = list.stream().filter(ar -> "20".equals(ar.getAnnounceStatus())).map(ArmReceiptPageVO::getReceiptedAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("查询订单的未支付金额paiedAmt:{}, salesHeadCode:{}", paiedAmt, salesHeadCode);
// 需要加上未认领的,但是支付方式是企业网银,支付宝、微信的金额(在途金额)
BigDecimal onlinePayAmtB = voList.stream().filter(ar -> "10".equals(ar.getAnnounceStatus()) && onLinePaymentChannel.contains(ar.getPaymentChannel())).map(ArmReceiptPageVO::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("查询订单的未支付金额onlinePayAmt:{}, salesHeadCode:{}", onlinePayAmtB, salesHeadCode);
paiedAmt = paiedAmt.add(onlinePayAmtB == null ? new BigDecimal(0) : onlinePayAmtB);
log.info("查询签收金额(应付金额):{}", paiedAmt);
}
BigDecimal notPayAmt = shouldPayAmt.subtract(paiedAmt);
log.info("查询订单的未支付金额出参shouldPayAmt:{}, paiedAmt:{}, notPayAmt:{}, salesHeadCode:{}", shouldPayAmt, paiedAmt, notPayAmt, salesHeadCode);
return notPayAmt;
}
Java中byte是8位带符号的二进制整数,Go中byte是8位无符号的二进制整数。
问题: 有符号整数溢出,无符号整数的环绕,无符号整数的减法问题,无符号整数和带符号整数混用