Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problem with BigDecimal

807598Sep 7 2006 — edited Sep 8 2006
My program purpose is to estimate the vlaue of constant e by using the formula

e= 1/1! +1/2! + 1/3! .....

The user can input any integer number then using for control statment & BigDecimal the program should calculate e.

my probelm why i am getting this error:

Please enter your Number: 25
25
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(Unknown Source)
at trainPack.EstimateEbyUser.main(EstimateEbyUser.java:35)
0.04
24

My code is:
import java.util.Scanner;
import java.math.BigDecimal;



public class EstimateEbyUser {

	public static void main(String[] args) {
	
		
		
		Scanner input =new Scanner(System.in);
		
		
		System.out.print("Please enter your Number: ");
		
		double number;
		
		number= input.nextDouble();
		
		BigDecimal numberBig =new BigDecimal(number);
		BigDecimal factorial =new BigDecimal(1.0D);
		BigDecimal value1 =new BigDecimal(1.0D);
		BigDecimal value2 =new BigDecimal(0.0D);
	
		for (;number>=1;number--)
		{
					
			factorial=factorial.multiply(numberBig);
			value1=new BigDecimal(1.0D).divide(numberBig);
			value2=value2.add(value1);
			numberBig=numberBig.subtract(new BigDecimal(1.0D));
			
			
		}
		System.out.println(value2);

	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 6 2006
Added on Sep 7 2006
6 comments
663 views