- 报错:
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. - 报错语句:
a.divide(b)); - 原因:
JAVA中如果用BigDecimal做除法的时候一定要在divide方法中传递第二个参数,定义精确到小数点后几位,否则在不整除的情况下,结果是无限循环小数时,就会抛出以上异常。 - 解决方法:
a.divide(b, 2, BigDecimal.ROUND_HALF_UP); - 总结:
注意这个divide方法有两个重载的方法,一个是传两个参数的,一个是传三个参数的:
//两个参数的方法: //传入除数 @param divisor value by which this {@code BigDecimal} is to be divided. //传入round的模式 @param roundingMode rounding mode to apply. //三个参数的方法: //传入除数 @param divisor value by which this {@code BigDecimal} is to be divided. //传入精度 @param scale scale of the {@code BigDecimal} quotient to be returned. //传入round的模式 @param roundingMode rounding mode to apply.
BigDecimal的divide方法报错
最新推荐文章于 2024-10-10 09:03:54 发布
本文详细解析了在Java中使用BigDecimal进行除法运算时,因未指定精度而导致的ArithmeticException异常。强调了在使用divide方法时,需定义小数点后的精确位数,以避免无限循环小数引发的问题。
1314

被折叠的 条评论
为什么被折叠?



