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

2013年7月2日 星期二

Android Service

For simplicity,
For those running in foreground, they are called 'Activity' (those applications we can see and use in our mobile)
For those running in background, they are called 'Service' (those we cannot see while running in background and keep consuming your mobile's RAM. Haha they are one of the evilest guys that make your mobile so slow)