# Basic Code: Looks right, gets funky

• October 10th, 2012, 08:13 PM
EmptyArsenal
Basic Code: Looks right, gets funky
I'm learning Java, and I've made a simple program called Savings that takes an initial amount, an annual deposit, and calculates balances with a 6.5% APY calculated annually. I added rounding to make it down to cents, but when it gets to the 7 iteration, it is no longer rounded. Here's the code:

public class Savings {
public static final double INTEREST_RATE = 0.065;

public static void main(String[] args) {
account(1000.0, 100, 25);
}

public static void account(double initial, int deposits, int years) {
double balance = initial;
for(int i = 1; i <= years; i++) {
double interest = Math.round(balance *
INTEREST_RATE * 100)/100.0;
System.out.print(i + "\t" + balance + "\t" + interest +
"\t" + deposits + "\t");
balance = balance + interest + deposits;
System.out.println(balance);
}
}
}

Output
1 1000.0 65.0 100 1165.0
2 1165.0 75.73 100 1340.73
3 1340.73 87.15 100 1527.88
4 1527.88 99.31 100 1727.19
5 1727.19 112.27 100 1939.46
6 1939.46 126.06 100 2165.52
7 2165.52 140.76 100 2406.2799999999997
8 2406.2799999999997 156.41 100 2662.6899999999996
9 2662.6899999999996 173.07 100 2935.7599999999998
10 2935.7599999999998 190.82 100 3226.58
11 3226.58 209.73 100 3536.31

If I add change the last balance to: balance = Math.round((balance + interest + deposits)*100)/100.0; it works fine. I just mostly am trying to figure out why the original gets a funky answer. I've worked through the debugger, and it just doesn't make sense.

Thanks for the help!
• October 10th, 2012, 08:36 PM
curmudgeon
Re: Basic Code: Looks right, gets funky
Even with rounded numbers, you're still doing division and still will not infrequently get a floating point number that cannot be represented exactly as decimal. I would recommend 2 solutions:

The "OK" solution:
Don't worry about rounding until you want to display the numbers. For example you could use printf to format your doubles for you (or DecimalFormat, or ...):

Code :

``` public static void account(double initial, int deposits, int years) { double balance = initial; for(int i = 1; i <= years; i++) { double interest = balance * INTEREST_RATE; double newBalance = balance + interest + deposits; System.out.printf("%2d: %7.2f %7.2f %d %8.2f%n", i, balance, interest, deposits, newBalance); balance = newBalance; } }```

The much better solution: Don't use floating point numbers for financial calculations as the accuracy is much too important for this. Use BigDecimals instead, and realize that you must accept the hit in memory usage and program speed as a price.
• October 11th, 2012, 10:32 AM
EmptyArsenal
Re: Basic Code: Looks right, gets funky
Great, thanks for the suggestions!
• October 11th, 2012, 01:04 PM
curmudgeon
Re: Basic Code: Looks right, gets funky
You're welcome!