问题场景:今天在处理BigDecimal 除法的时候出现
问题描述::java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result。
报错处:sub.divide(oneCountMoneyNum)
问题原因:java在处理BigDecimal做除法的时候一定要在divide的方法中不传递第二个参数,定义到小数点后几位,否则在不整除的情况下,结果会出现无线循环小数,就会抛出以上异常
解决办法:sub.divide(oneCountMoneyNum,2,BigDecimal.ROUND_HALF_UP)
所以注意:
divide方法有两个重载的方法,一个是传两个参数的,一个是传三个参数的:
两个参数的方法:
@param divisor value by which this {@code BigDecimal} is to be divided. 传入除数
@param roundingMode rounding mode to apply. 传入round的模式
三个参数的方法:
@param divisor value by which this {@code BigDecimal} is to be divided. 传入除数
@param scale scale of the {@code BigDecimal} quotient to be returned. 传入精度
@param roundingMode rounding mode to apply. 传入round的模式
本文详细解析了在Java中使用BigDecimal进行除法运算时遇到的ArithmeticException异常,阐述了异常产生的原因在于未指定结果的小数位数,导致无限循环小数无法精确表示。文章提供了具体的解决方法,即在divide方法中指定精度和舍入模式。
13万+

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



