2013年7月4日 星期四

BigDecimal.divide ArithmeticException

Sometimes, when we are using the divide function of BigDecimal like this:
BigDecimal d1 = new BigDecimal(1);
BigDecimal d2 = new BigDecimal(3);
BigDecimal result= d1.divide(d2); // 1/3 = 0.33333333....

The following exception will be thrown:
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

This is caused as the division results into a recurring decimal which cannot be represented by BigDecimal.
To solve this, simply add rounding parameters into the function divide(divisor, scale, roundingMode):
BigDecimal d1 = new BigDecimal(1);
BigDecimal d2 = new BigDecimal(3);
BigDecimal result= d1.divide(d2, 2, BigDecimal.ROUND_HALF_UP); // 1/3 = 0.33

沒有留言:

張貼留言