Javascript yearly compound interest calculation

1.7k views Asked by At

When this code runs, it outputs "Annual Account Balance for Year (i) = 100" for every year. Clearly the answer shouldn't be 100 every time, but I can't see what I am doing wrong in the equation.

var invest;
var rate;
var amount; 

rate = 0.08;
invest = 100,000;

    for(var i=1;i<=10;i++){
        amount = ((parseInt(invest)) * (1.0 + (parseInt(rate)) * (parseInt(i))))
        document.write("Annual Account Balance for Year " + i + " = " + amount + "<br>");
    }
2

There are 2 answers

1
johnnyRose On

Instead of calling parseInt(rate), you need to be calling parseFloat(rate) - though according to your code, these are numbers - so they don't need to be parsed regardless.

parseInt will parse an Integer from a string (though it will still be of type 'Number'). In this case, it is actually returning 0 instead of the 0.08 that you want to be using. Calling parseInt on a number will convert it from a number to a string, and then back again... Which is essentially useless.

Additionally, as Oriol stated, you can't add commas to numbers in JavaScript.

0
Halcyon On

parseInt(0.08) gives 0 so the math doesn't do anything. You don't need to parse your variables here since you define them yourself. You really only ever need to parse if you read from user input.

Also your math for the interest is bad. You need to calculate interest over interest.

This script gives the correct* output:

var invest;
var rate;
var amount; 

rate = 0.08;
invest = 100000;

amount = invest;
for(var i = 1; i <= 10; i++){
    amount = amount * (1.0 + rate);
    document.write("Annual Account Balance for Year " + i + " = " + amount + "<br>");
}

output:

Annual Account Balance for Year 1 = 108000
Annual Account Balance for Year 2 = 116640.00000000001
Annual Account Balance for Year 3 = 125971.20000000003
Annual Account Balance for Year 4 = 136048.89600000004
Annual Account Balance for Year 5 = 146932.80768000006
Annual Account Balance for Year 6 = 158687.43229440006
Annual Account Balance for Year 7 = 171382.42687795206
Annual Account Balance for Year 8 = 185093.02102818823
Annual Account Balance for Year 9 = 199900.4627104433
Annual Account Balance for Year 10 = 215892.49972727877

// this would be the output with your bad math:

Annual Account Balance for Year 1 = 108000
Annual Account Balance for Year 2 = 115999.99999999999 // float funny business, beware!
Annual Account Balance for Year 3 = 124000
Annual Account Balance for Year 4 = 132000
Annual Account Balance for Year 5 = 140000
Annual Account Balance for Year 6 = 148000
Annual Account Balance for Year 7 = 156000
Annual Account Balance for Year 8 = 164000
Annual Account Balance for Year 9 = 172000
Annual Account Balance for Year 10 = 180000

* Since we're dealing with float values here be very wary of it's limited precision.