gmosx.ninja

Nasty Java catch

Some time ago, I wrote about a nasty JavaScript catch. Well, it seems that no language is immune from nasty surprises, so here comes one for Java:

BigDecimal value = new BigDecimal("0.31");
BigDecimal oldValue = new BigDecimal("0.34");
BigDecimal ratio = value.divide(oldValue);

throws:

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

Funky, huh? Let me offer a quick fix:

BigDecimal ratio = value.divide(oldValue, BigDecimal.ROUND_HALF_EVEN);

For some intuition (in Khan's parlance), have a look here.