BigDecimal.divide 报ArithmeticException异常

128 阅读1分钟

BigDecimal.divide 报ArithmeticException异常

使用BigDecimal.divide进行两数相除时,如果两数都是整数且除不尽时,如下:

new BigDecimal("2").divide(new BigDecimal("3")).intValue();

则会报ArithmeticException异常,如下:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
	at java.math.BigDecimal.divide(BigDecimal.java:1693)
	at com.three.erp.salary.Test.main(Test.java:11)

原因是两数都是整数,则默认计算结果的小数位数为0,但结果又是除不尽的数导致系统无法生成有效数字,所以只需要设置一下divide方法中设置小数位和舍入模式就可以了,如下:

new BigDecimal("2").divide(new BigDecimal("3"), 1, BigDecimal.ROUND_DOWN).intValue();