• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

4小时前 6次浏览

# BigDecimal做除法时的错误

``````//随手打出来两个数字相除
new BigDecimal("3213").divide(new BigDecimal("847"))

//报错信息是Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
//翻译过来就是 非终止小数扩展；没有精确的十进制结果。
//其实就是除出来的数字是循环小数,要求确定小数点后保留几位 所以1/3也会报错
``````

@param divisor value by which this {@code BigDecimal} is to be divided. 传入除数
@param roundingMode rounding mode to apply. 传入round的模式

``````numA.divide(numB,BigDecimal.ROUND_HALF_UP)
``````

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

``````return numA.divide(numB,4,BigDecimal.ROUND_HALF_UP);
``````

``````BigDecimal.ROUND_HALF_UP //小学学习的四舍五入
BigDecimal.ROUND_DOWN 	 //向下取整
BigDecimal.ROUND_UP 	 //向上取整

//结果小数 3.7933884298
numA.divide(numB,4,BigDecimal.ROUND_HALF_UP); //3.7934四舍五入
numA.divide(numB,4,BigDecimal.ROUND_DOWN); //3.7933直接舍去四位之后的
numA.divide(numB,3,BigDecimal.ROUND_UP); //3.794直接向上取值
``````