0
BigDecimal bd1 = new BigDecimal(8757).divide(new BigDecimal(12));

I get the following exception:

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

Why is it the case? The result of the division should be 729.75 which has a terminating decimal expansion (.75).

manash
  • 6,985
  • 12
  • 65
  • 125
  • 2
    are you sure that this is the cause? it´s working fine, atleast for me – SomeJavaGuy Jan 21 '16 at 15:57
  • 2
    Are you **sure** this is the code you're running? It executes perfectly on my machine, returning 729.75. – Mureinik Jan 21 '16 at 15:58
  • Same here. What version of Java are you using. Could you include more details, for example the rest of the code around where you are using this? – pczeus Jan 21 '16 at 16:10
  • If that helps, the code is executed when running a unit test using Eclipse. The JDK version is 1.8.0_66. That may be a bug... – manash Jan 21 '16 at 18:25

1 Answers1

0

I found what the issue was. The code that was actually executed is as follows:

public class ClassA {   
    public static final BigDecimal BD2= new BigDecimal(12);
}

public ClassB {
    public static final BigDecimal BD1 = new BigDecimal(8757);
    public static final BigDecimal RESULT = BD1.divide(ClassA.BD2);
}

BD2 was not initialized when the divide() method was called (I checked that using a breakpoint). However, I still think there is a bug since it should not throw this exception in this case, which is completely unrelated to what is happening. I guess BD2 is null when divide() is called.

manash
  • 6,985
  • 12
  • 65
  • 125