java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal ...

今天在写一个JAVA程序的时候出现了异常:java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result
发现报错的语句是:java

1
foo.divide(bar));

原来JAVA中若是用BigDecimal作除法的时候必定要在divide方法中传递第二个参数,定义精确到小数点后几位,不然在不整除的状况下,结果是无限循环小数时,就会抛出以上异常。
解决方法:app

1
foo.divide(bar, 2 , BigDecimal.ROUND_HALF_UP);

注意这个divide方法有两个重载的方法,一个是传两个参数的,一个是传三个参数的:ide

两个参数的方法:this

@param divisor value by which this {@code BigDecimal} is to be divided. 传入除数spa

@param roundingMode rounding mode to apply. 传入round的模式code

三个参数的方法:ci

@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的模式it

相关文章
相关标签/搜索