完美解决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


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



相关文章
|
7月前
|
算法 C# C++
HALCON error #1201: Wrong type of control parameter: 1 in operator threshold
HALCON error #1201: Wrong type of control parameter: 1 in operator threshold
|
9月前
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解决方法
524 0
Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?)
Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?)
338 0
Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?)
Multiple substitutions specified in non-positional format; did you mean to add BUG(7)
Multiple substitutions specified in non-positional format; did you mean to add BUG(7)
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 ……
189 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'
357 0
|
数据库
Incorrect result size: expected 1, actual 2
Incorrect result size: expected 1, actual 2
739 0
|
IDE 开发工具
C - error: converting to execution character set:Illegal byte sequence
C - error: converting to execution character set:Illegal byte sequence
1089 0
C - error: converting to execution character set:Illegal byte sequence
|
关系型数据库 MySQL 数据库
当你遇到Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect string value:
当你遇到Error: ER_TRUNCATED_WRONG_VALUE_FOR_FIELD: Incorrect string value: