Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: Java : For Loop gets an unexpected 700.000001 result.

1. ## Java : For Loop gets an unexpected 700.000001 result.

Hello guys,

Can anyone find something in this code strange. It pops out an unexpected 700.0000001 meanwhile all others put 500.00, 400.00,300.00

Result:

The interest at 1 is 100.0
The interest at 2 is 200.0
The interest at 3 is 300.0
The interest at 4 is 400.0
The interest at 5 is 500.0
The interest at 6 is 600.0
The interest at 7 is 700.0000000000001
The interest at 8 is 800.0
The interest at 9 is 900.0
The interest at 10 is 1000.0

The code is:
double amount = 10000;
for(int interestRate = 1; interestRate < 11; interestRate++){
double result = calculateInterest(10000, interestRate);
System.out.println("The interest at " + interestRate + " is " + result );
}

It uses this method:
public static double calculateInterest(double amount, double interestRate) {
return(amount * (interestRate / 100));
}

Any thought ?

--- Update ---

Solution is

String.format("%.2f", )

System.out.println("The interest at " + interestRate + " is " + String.format("%.2f", result ));

3. ## Re: Java : For Loop gets an unexpected 700.000001 result.

That's what happens with limited precision in programming languages. You can divide by a number and then multiply the quotient the same number and get a result different from the starting number. The differences are usually very small but can create havoc in some situations. So you need to either round to some specific precision or specify a field width using System.out.printf(). And you can check out Norm's suggested link. It is not light reading for the un-initiated.

Regards,
Jim