mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2026-05-29 18:57:11 +08:00
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:
@@ -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;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user