Calculating future value with compound interest with JavaScript

后端 未结 6 1568
悲哀的现实
悲哀的现实 2021-02-04 19:39

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

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-04 20:08

    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;
    

提交回复
热议问题