How to fix "java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result."

Overview

In this tutorial, we show you how to fix the error messages "java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result." when we use java.math.BigDecimal to divide two values.



How-to-fix-Non-terminating-decimal-expansion

Watch Tutorial



Error Messages

The following simple code snippet demonstrates the error messages

package com.jackrutorial;

import java.math.BigDecimal;

public class Test {

 public static void main(String[] args) {
  BigDecimal num1 = new BigDecimal("10");
  BigDecimal num2 = new BigDecimal("3");
  
  BigDecimal result = num1.divide(num2);
  
  System.out.println(result);
 }
}

When the above code is executed, the expected exception is encountered as the following error messages

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

How to fix those error messages?

You have to modify the source code below

Way 1:

BigDecimal result = num1.divide(num2, 2, RoundingMode.HALF_DOWN);

2 is scale of the BigDecimal quotient to be returned.
RoundingMode.HALF_DOWN is Rounding mode to apply. The Rounding Mode Enum constants are UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP, and UNNECESSARY.

The updated Test class will have the following code:

package com.jackrutorial;

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

public class Test {

 public static void main(String[] args) {
  BigDecimal num1 = new BigDecimal("10");
  BigDecimal num2 = new BigDecimal("3");
  
  BigDecimal result = num1.divide(num2, 2, RoundingMode.HALF_DOWN);
  
  System.out.println(result);
 }
}

The output of the above code is
3.33

Way 2:

num1.divide(num2, MathContext.DECIMAL128)
MathContext.DECIMAL32
MathContext.DECIMAL64
MathContext.DECIMAL128
package com.jackrutorial;

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

public class Test {

 public static void main(String[] args) {
  BigDecimal num1 = new BigDecimal("10");
  BigDecimal num2 = new BigDecimal("3");
  
  BigDecimal result = num1.divide(num2, MathContext.DECIMAL128);
  
  System.out.println(result);
 }
}

The output of the above code is
3.333333333333333333333333333333333
Previous Post
Next Post

post written by: