今天使用BigDecimal数据类型做除法的时候,遇到以下报错:
Method threw ‘java.lang.ArithmeticException’ exception.
Non-terminating decimal expansion; no exact representable decimal result.
经过排查发现是当不整除,出现无限循环小数时,就会抛异常的。
比如10/3 =3.33333… 就会出现异常
解决办法:
1.设置精度
具体代码如下:
new BigDecimal(10).divide(new BigDecimal(3),2,BigDecimal.ROUND_HALF_UP));
源码如下:
1 public BigDecimal divide(BigDecimal divisor, int scale, int roundingMode) { 2 if (roundingMode < ROUND_UP || roundingMode > ROUND_UNNECESSARY) 3 throw new IllegalArgumentException("Invalid rounding mode"); 4 if (this.intCompact != INFLATED) { 5 if ((divisor.intCompact != INFLATED)) { 6 return divide(this.intCompact, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode); 7 } else { 8 return divide(this.intCompact, this.scale, divisor.intVal, divisor.scale, scale, roundingMode); 9 } 10 } else { 11 if ((divisor.intCompact != INFLATED)) { 12 return divide(this.intVal, this.scale, divisor.intCompact, divisor.scale, scale, roundingMode); 13 } else { 14 return divide(this.intVal, this.scale, divisor.intVal, divisor.scale, scale, roundingMode); 15 } 16 } 17 }
————————————————
版权声明:本文为CSDN博主「严孝祥 yanxiaoxiang」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42280076/article/details/108082470