public List<BigDecimal> divideRedPacket(BigDecimal totalAmount, int num) { List<BigDecimal> list = new ArrayList<>(); BigDecimal remainingAmount = totalAmount; Random random = new Random(); for (int i = 0; i < num; i++) { if (i == num - 1) { list.add(remainingAmount); } else { BigDecimal maxAmount = remainingAmount.divide(new BigDecimal(num - i), 2, BigDecimal.ROUND_DOWN) .multiply(new BigDecimal("2")); BigDecimal amount = maxAmount.multiply(new BigDecimal(random.nextDouble() + 0.01)) .setScale(2, BigDecimal.ROUND_DOWN); list.add(amount); remainingAmount = remainingAmount.subtract(amount); } } return list; }优化以上代码,要求添加两个参数,两个参数分别控制几个红包的小数点第二位为几
时间: 2024-03-22 10:39:40 浏览: 148
可以通过将小数点第二位按照要求进行舍入来实现。优化后的代码如下:
```
public List<BigDecimal> divideRedPacket(BigDecimal totalAmount, int num, int scale) {
List<BigDecimal> list = new ArrayList<>();
BigDecimal remainingAmount = totalAmount;
Random random = new Random();
for (int i = 0; i < num; i++) {
if (i == num - 1) {
list.add(remainingAmount.setScale(scale, BigDecimal.ROUND_DOWN));
} else {
BigDecimal maxAmount = remainingAmount.divide(new BigDecimal(num - i), scale + 1, BigDecimal.ROUND_DOWN)
.multiply(new BigDecimal("2"));
BigDecimal amount = maxAmount.multiply(new BigDecimal(random.nextDouble() + 0.01))
.setScale(scale, BigDecimal.ROUND_DOWN);
list.add(amount);
remainingAmount = remainingAmount.subtract(amount);
}
}
return list;
}
```
其中,第三个参数 `scale` 控制小数点第二位为 `scale`。在计算最大金额时,将小数点精度设为 `scale + 1`,然后再通过 `.setScale(scale, BigDecimal.ROUND_DOWN)` 将小数点第二位舍入为 `scale`。在计算实际金额时,直接通过 `.setScale(scale, BigDecimal.ROUND_DOWN)` 将小数点第二位舍入为 `scale`。
阅读全文