Search code examples
javascriptfinance

Calculating future value with compound interest with JavaScript


I'm trying to work on a script where the user inserts a monthly income and gets the future value with compound interest after 30 years. As it is now, I've assigned some values for testing purposes.

// Future Value
var investment = 800;
var annualRate = 2;
var monthlyRate = annualRate / 12 / 100;
var years = 30;
var months = years * 12;
var futureValue = 0;

for ( i = 1; i <= months; i++ ) {
    futureValue = futureValue + investment * Math.pow(1 + monthlyRate, months);
}

Problem is, I'm actually building this from an Excel spreadsheet that's using the built-in FV() formula and when cross checking, my results are totally off... Any idea what I'm doing wrong since I'm not into finance math at all. Thanks in advance.


Solution

  • The Math.pow is unnecessary, since you are calculating and incrementing futureValue month by month. Simply multiply by 1 + monthlyRate. You also want to add the current value of the investment to the new investment before multiplying:

    for ( i = 1; i <= months; i++ ) {
       futureValue = (futureValue + investment) * (1 + monthlyRate);
    }
    

    Alternatively, you can also calculate this in one go with the following formula:

    futureValue = investment * (Math.pow(1 + monthlyRate, months) - 1) / monthlyRate;