"Non-terminating decimal expansion; no exact representable decimal result" happens even when divide by 100

Kazi Islam picture Kazi Islam · Jul 23, 2013 · Viewed 14.8k times · Source

My java code is running on HP-UX hpdev B.11.23 U ia64 and sometimes it will produce the following exception: java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

The code that causes it:

BigDecimal p_Change = (BigDecimal)record.get("P_CHNG");
p_Change.divide(new BigDecimal(100));

record is simple a Collection of column values from a sql query.p_change comes from a table in an Oracle database where the column is NUMBER(10,2).

I understand why this happens.The frequency is random, it will divide fine with the same data sometimes. I am just wondering if this has something to do with the hardware.

Answer

James Grammatikos picture James Grammatikos · Jul 23, 2013

Could you do a system.out on your value for p_Change?

BigDecimal p_Change = new BigDecimal(Math.PI);
System.out.println(p_Change.divide(new BigDecimal(100)));

// yields this 0.03141592653589793115997963468544185161590576171875

It's identical to your code, with just the substitution of p_Change with pi

The issue probably has to deal with you not entering a rounding mode. Try using

p_Change.divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP);