fix(Money): 为 divide 和 divideBy 方法增加除零校验

当除数 val 为 0 时,Math.round(cent / 0.0) 会得到 Long.MAX_VALUE 分(约 9.2 * 10^16 元),
而不是抛出异常,导致计算结果错误且无任何提示。
增加显式的除零检查,在 val == 0 时抛出 ArithmeticException。
This commit is contained in:
Busyliu
2026-03-02 05:41:12 +00:00
committed by Gitee
parent 8710d04640
commit 885fd28de6

View File

@@ -621,6 +621,9 @@ public class Money implements Serializable, Comparable<Money> {
* @return 相除后的结果。
*/
public Money divide(double val) {
if (val == 0) {
throw new ArithmeticException("Division by zero");
}
return newMoneyWithSameCurrency(Math.round(cent / val));
}
@@ -635,7 +638,10 @@ public class Money implements Serializable, Comparable<Money> {
* @return 累除后的结果。
*/
public Money divideBy(double val) {
this.cent = Math.round(this.cent / val);
if (val == 0) {
throw new ArithmeticException("Division by zero");
} this.cent = Math.round(this.cent / val);
return this;
}