What causes "Non-terminating decimal expansion" exception from BigDecimal.divide?

ChadNC picture ChadNC · May 15, 2012 · Viewed 57.6k times · Source

I've used BigDecimals before but not very often and I was working on something this morning and I kept getting the following exception:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion;
no exact representable decimal result.
    at java.math.BigDecimal.divide(BigDecimal.java:1594)

I was attempting to set the scale and use rounding to eliminate the problem like so:

    BigDecimal bd1 = new BigDecimal(1131).setScale(2,BigDecimal.ROUND_HALF_UP);
    BigDecimal bd2 = new BigDecimal(365).setScale(2,BigDecimal.ROUND_HALF_UP);
    BigDecimal bd3 = bd1.divide(bd2).setScale(2,BigDecimal.ROUND_HALF_UP);
    System.out.println("result: " + bd3);

However, I keep getting the same exception. Anyone able to show me where I have made a mistake?

Answer

assylias picture assylias · May 15, 2012

Non-terminating decimal need rounding

When using divide you should use a MathContext with RoundingMode in case the exact result has an infinite number of decimals.

Such is your case:

MathContext mc = new MathContext(2, RoundingMode.HALF_UP) ;
BigDecimal bd3 = bd1.divide(bd2, mc);

Alternatively call divide passing the scale and rounding mode.

BigDecimal bd3 = bd1.divide(bd2, RoundingMode.HALF_UP);