Search code examples
javaexceptionbigdecimal

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


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?


Solution

  • 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 with a rounding mode to use the scale of the numerator (bd1 in the example below):

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