Close

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

Java Exceptions Java API 


Class:

java.lang.ArithmeticException

java.lang.Objectjava.lang.Objectjava.lang.Throwablejava.lang.Throwablejava.io.SerializableSerializablejava.lang.Exceptionjava.lang.Exceptionjava.lang.RuntimeExceptionjava.lang.RuntimeExceptionjava.lang.ArithmeticExceptionjava.lang.ArithmeticExceptionLogicBig


Cause of the exception

This exception is thrown when the result of a division is recurring (never ending), and we haven't specified rounding mode/scale. In other words, BigDecimal won't know how to represent a recurring division result if we haven't specified to what decimal places the result should be rounded, so it throws this exception.

package com.logicbig.example.arithmeticexception;

import java.math.BigDecimal;

public class ArithmeticExceptionNoExactRepresentable {
public static void main(String... args) {
BigDecimal a = new BigDecimal(5);
BigDecimal b = new BigDecimal(3);
BigDecimal result = a.divide(b);
System.out.println(result);
}
}

Output

java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide (BigDecimal.java:1723)
at com.logicbig.example.arithmeticexception.ArithmeticExceptionNoExactRepresentable.main (ArithmeticExceptionNoExactRepresentable.java:18)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:564)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:282)
at java.lang.Thread.run (Thread.java:832)

5/3 is 1.66666666.....





Fixing the exception

To fix this error we need to specify scale and rounding mode by using following overloaded method:
BigDecimal#divide(BigDecimal divisor, int scale, RoundingMode roundingMode)

package com.logicbig.example.arithmeticexception;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class ArithmeticExceptionNoExactRepresentableFix {
public static void main(String... args) {
BigDecimal a = new BigDecimal(5);
BigDecimal b = new BigDecimal(3);
BigDecimal result = a.divide(b, 3, RoundingMode.HALF_UP);
System.out.println(result);
}
}

Output

1.667




See Also