Simon
Simon

Reputation: 2538

Compounding interest calculator with monthly contributions

I'm really struggling with what seems should be a fairly simple calculation...

I would like to calculate the compounding interest of an initial investment, with monthly contributions...

This is what I have so far:

function makeInvestingCalculation() {
  let princ = 3500; // start deposit
  let add = 250; // monthly deposit (need plus it every year)
  let rate = 12 / 100; // interest rate divided to create decimal
  let months = (10 * 12); //10 years of monthly contributions
  for (let i = 0; i < months; i++) {
    if (i != 0) {
      princ += add;
    }
    princ += princ * rate;
  }
  console.log(princ.toFixed(2)); //4498379090.49
}

makeInvestingCalculation();

This produces 4498379090.49 which is clearly incorrect.

The correct answer is supposed to be 69,636.12 but I am unable to find this...

Any help would be greatly appreciated.

Upvotes: 0

Views: 1809

Answers (2)

Fahad Shakeel
Fahad Shakeel

Reputation: 11

I read the answer of @chiliNUT, and it's perfect, I want to add a little bit to it, as you know deposits can be made start and end of the month and most calculator uses the end-of-month technique so here is the code for that.

 let princ = 10000; // start deposit
let add = 500; // monthly deposit (need plus it every year)
let rate = 0.06; // interest rate divided to create decimal
let months = (41 * 12); //41 years of monthly contributions
for (let i = 1; i <= months; i++) {

    princ += princ * (rate / 12);
    princ += add;
    console.log(princ);
}
console.log(princ.toFixed(2)); 

Upvotes: 1

chiliNUT
chiliNUT

Reputation: 19592

The main issue is (as @CertainPerformance correctly pointed out)

princ += princ * rate;

Since you are compounding monthly, you need to divide the annual rate by 12 (months), so

princ += princ * (rate/12);

The second, subtler issue is

for (let i = 0; i < months; i++) {
    if (i != 0) {
      princ += add;
    }

you are skipping the first payment, which might make since intuitively since you aren't making a contribution in the 0th month, however, since the loop condition is < months and not <= months you are also skipping the last contribution, so your loop stops 1 contribution early. Conceptually, the loop condition makes more sense to me as this:

for(let i=1; i <= 12*10; i++)

so then

  let princ = 3500; // start deposit
  let add = 250; // monthly deposit (need plus it every year)
  let rate = 12 / 100; // interest rate divided to create decimal
  let months = (10 * 12); //10 years of monthly contributions
  for (let i = 1; i <= months; i++) {
    princ += add;
    princ += princ * (rate / 12);
    console.log(princ);
  }
  console.log(princ.toFixed(2)); //69636.12

Upvotes: 1

Related Questions