完美解决Non-terminating decimal expansion; no exact representable decimal result.异常

简介: 完美解决Non-terminating decimal expansion; no exact representable decimal result.异常

我们在使用BigDecimal进行精确计算时常常会出现Non-terminating decimal expansion; no exact representable decimal result.异常。


0f9694dd3b874bdc8cfadc5ac4c42090.png

出现这个异常的原因在于 BigDecimal 是不可变的、任意精度的有符号十进制数,所以可以做精确计算。但在除法中,准确的商可能是一个无限长的十进制扩展;例如,1 除以 3 所得的商。我们在做除法时,没有指定舍入模式,并且无法表示为准确的结果,因此抛出了这个异常(java.lang.ArithmeticException)。

知道了原因我们该如何解决呢?

  • 只需要在 divide() 方法中传入 MathContext 对象或 RoundingMode 对象,指定精度和舍入模式就可以解决该问题。

RoundingMode 对象的八种舍入模式


常量名 说明
CEILING 向正无限大方向舍入
DOWN 向零方向舍入
FLOOR 向负无限大方向舍入

HALF_DOWN 向最接近数字方向舍入,如果与两个相邻数字的距离相等,则向下舍入
HALF_EVEN 向最接近数字方向舍入,如果与两个相邻数字的距离相等,则向相邻的偶数舍入
HALF_UP 向最接近数字方向舍入,如果与两个相邻数字的距离相等,则向上舍入
UNNECESSARY 断言具有精确结果


这里要根据业务选择合适的方法没有最好的只有最适合的。本文采用的是在divide运算时指定保留两位小数点的方法解决。详情看下图。


dc1a324b043b41e3bd41c4723383b171.png


修改完成后经测试。该问题成功解决!



相关文章
YOLO V5出现RuntimeError: result type Float can‘t be cast to the desired output type long int解决方法
YOLO V5出现RuntimeError: result type Float can‘t be cast to the desired output type long int解决方法
614 0
Optional int parameter ‘id‘ is present but cannot be translated into a null value due to being ……
Optional int parameter ‘id‘ is present but cannot be translated into a null value due to being ……
248 0
|
Windows
Illegal character in opaque part at index
Illegal character in opaque part at index
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
425 0
Julia:报错 no method matching increment_deriv!(::Float64, ::Float64)
描述是 `no method matching increment_deriv!(::Float64, ::Float64)` ,找不到该方法。
94 0
|
IDE 开发工具
C - error: converting to execution character set:Illegal byte sequence
C - error: converting to execution character set:Illegal byte sequence
1161 0
C - error: converting to execution character set:Illegal byte sequence
成功解决ValueError: Number of passed names did not match number of header fields in the file
成功解决ValueError: Number of passed names did not match number of header fields in the file
|
数据库
Incorrect result size: expected 1, actual 2
Incorrect result size: expected 1, actual 2
800 0
|
关系型数据库 MySQL 数据库
当你遇到Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect string value:
当你遇到Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect string value:
成功解决ValueError: Parameter values for parameter (n_estimators) need to be a sequence.
成功解决ValueError: Parameter values for parameter (n_estimators) need to be a sequence.
成功解决ValueError: Parameter values for parameter (n_estimators) need to be a sequence.