454,645 Members | 1,328 Online Need help? Post your question and get tips & solutions from a community of 454,645 IT Pros & Developers. It's quick & easy.

# java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representa

 P: 20 here is my code.but there is something wrong when I using BigDecimal class. Expand|Select|Wrap|Line Numbers package javaapplication30;   import java.math.BigDecimal;   public class Main {     public static void main(String[] args) {    Main a=new Main();      BigDecimal sum=new BigDecimal(0);     for(int i=3;i<=100;i++){               sum=a.R(i).add(sum);       }System.out.println(sum);   }   BigDecimal R(int m){      int p,q;         BigDecimal sum=new BigDecimal(0);     for(p=1;p<=m;p++){         for(q=p+1;q<=m;q++){             if(p+q>=m){                 if(isCoprime(p,q)){                                     BigDecimal x = new BigDecimal(1);                                 BigDecimal y = new BigDecimal((p*q));                                 BigDecimal result=x.divide(y);                  sum=sum.add(result);                                 }                 }         }     } return sum;     } boolean isCoprime(int p,int q){     int i;     if(p==1)return true;     if(p==q-1)return true;     if(q%p==0)return false;     if(p==3)return true;     for(i=2;i*i<=p;i++){      if(p%i==0){          if(q%i==0||q%(p/i)==0)break;      }         }if(i*i<=p+1)return false;     return true; } } here is output.please help me... Expand|Select|Wrap|Line Numbers init: deps-jar: Compiling 1 source file to C:\Users\seeker-PC\Documents\NetBeansProjects\JavaApplication30\build\classes warning: [options] bootstrap class path not set in conjunction with -source 1.5 1 warning compile: run: 0.5 Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.         at java.math.BigDecimal.divide(BigDecimal.java:1616)         at javaapplication30.Main.R(Main.java:27)         at javaapplication30.Main.main(Main.java:12) Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds Oct 20 '13 #1

The problem is when you divide 1 by 3; the resulting expression cannot be represented by a finite number of decimal places (as it is 0.333333333...). To solve this you have to pass a scale to which the result should be rounded and a rounding mode. So this would mean using this divide method, which would look something like this:
Expand|Select|Wrap|Line Numbers
1. BigDecimal result = x.divide(y, 3, BigDecimal.ROUND_HALF_UP); 