Non-terminating decimal expansion no exact representable decimal result in Java


In this Example we are going to understanding the exception, while dividing the BigDecimal values.

Error Message :
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
       at java.base/java.math.BigDecimal.divide(BigDecimal.java:1722)
       at com.si.exceptions.ArthimeticException.main(ArthimeticException.java:10)

Error Description :

package com.si.exceptions;

import java.math.BigDecimal;

public class ArthimeticException {

       public static void main(String[] args) {
              BigDecimal b1 = new BigDecimal(8.6);
              BigDecimal b2 = new BigDecimal(6.8);
              System.out.println(b1.divide(b2));
       }
}

      
      
In the above example ,the red background color line is giving the exception.
Here we are dividing the Big decimal values division.This decimals will give non terminating decimal expansion so we wont get exact result that's why we will get Arithmetic Exception.

Solution:


To avoid this exception We are using MathContext.DECIMAL32  method which will give the number of digits to be used and the results are rounded to this precision.It internally used some algorithm to make the value rounding mode.


package com.si.exceptions;

import java.math.BigDecimal;
import java.math.MathContext;

public class ArthimeticException {

       public static void main(String[] args) {
              BigDecimal b1 = new BigDecimal(8.6);
              BigDecimal b2 = new BigDecimal(6.8);
              System.out.println(b1.divide(b2,MathContext.DECIMAL32));
       }
}

Output:
1.264706

Share this post :

Post a comment

Please share your valuable feedback and share this article in social media.

 
Support : Ranga Rajesh Kumar
Copyright © 2019. Error Solution - All Rights Reserved
Site Designed by Ranga Rajesh Kumar