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 18:39:17 浏览: 51
bigdecimal转integer.txt
好的,我可以帮您优化这段代码,加入两个参数来控制小数点位数。以下是优化后的代码:
```java
public List<BigDecimal> divideRedPacket(BigDecimal totalAmount, int num, int decimalPlaces, int fixedValue) {
List<BigDecimal> list = new ArrayList<>();
BigDecimal remainingAmount = totalAmount;
Random random = new Random();
BigDecimal factor = new BigDecimal("10").pow(decimalPlaces);
for (int i = 0; i < num; i++) {
if (i == num - 1) {
list.add(remainingAmount.setScale(decimalPlaces, BigDecimal.ROUND_DOWN));
} else {
BigDecimal maxAmount = remainingAmount.divide(new BigDecimal(num - i), decimalPlaces, BigDecimal.ROUND_DOWN)
.multiply(new BigDecimal("2"));
BigDecimal amount = maxAmount.multiply(new BigDecimal(random.nextDouble() + 0.01))
.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
if (fixedValue != -1) {
amount = amount.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
amount = amount.setScale(fixedValue, BigDecimal.ROUND_HALF_UP);
}
list.add(amount.divide(factor, decimalPlaces, BigDecimal.ROUND_DOWN));
remainingAmount = remainingAmount.subtract(amount);
}
}
return list;
}
```
其中,`decimalPlaces` 参数控制小数点后的位数,`fixedValue` 参数控制小数点第二位保留多少位。如果 `fixedValue` 参数为 -1,则不进行保留操作。
阅读全文