allig256
allig256

Reputation: 45

Compounding interest monthly with a deposit

I want to compound interest on a weekly/fortnightly/monthly/annual basis.

I also want an option to have a deposit amount that can be added in.

I have already tried the standard formula of calculating the final amount accrued, as seen here:

formula
(source: gstatic.com)

For example here is my method for calculating the interest compounding weekly:

function calculateWeekly(state: any) {
  const { savings, deposit ,interest, timePeriodSelector, timePeriodLength } = state;

  let numberOfYears = 0;

  if (timePeriodSelector === "weekly") {
    numberOfYears = timePeriodLength / weeksInAYear;
  } else if (timePeriodSelector === "fortnightly") {
    numberOfYears = (timePeriodLength / weeksInAYear) * 2;
  } else if (timePeriodSelector === "monthly") {
    numberOfYears = (timePeriodLength / weeksInAYear) * weeksInAMonth;
  } else if (timePeriodSelector === "annually") {
    numberOfYears = (timePeriodLength / weeksInAYear) * weeksInAYear;
  }

  const weeklyRate = interest / 100 / weeksInAYear;
  const lengthOfCompunding = numberOfYears * weeksInAYear;

  let startingFigure = parseInt(savings) + parseInt(deposit);

  //total gets added on for every time cycle of week
  let total =
    (startingFigure * (Math.pow(1 + weeklyRate, lengthOfCompunding) - 1)) / weeklyRate;

  return roundToTwoDP(total);
}

The issue with the above code is that the deposit gets added into the calculation every time the interest accrues. So a deposit of $10 weekly for 10 weeks will actually get added up to $100.

I attempted a method to accrue the interest using a loop for each week here:

  // loops how many times to compound the interest
  for(let i = numberOfYears - (1/weeksInAYear); i > 0; i-= (1/weeksInAYear)){
    let interestGained = (total * (Math.pow((1 + weeklyRate), lengthOfCompunding))) - total;
    total += interestGained + savings;
  }

Thanks for any help!

Upvotes: 3

Views: 515

Answers (1)

Andrew Koster
Andrew Koster

Reputation: 1835

This should do what you want:

const range = (min, max) => {

    const size = 1 + max - min

    return [...Array(size).keys()].map(n => n + min)
}

const weeksInAYear = 52

const addWeeklyInterest = interestRatePerWeek => (savings, _) => savings + savings * interestRatePerWeek

const calculateTotal = (savings, numberOfYears, interestRatePerWeek) => {

    const numberOfWeeks = numberOfYears * weeksInAYear

    return range(1, numberOfWeeks).reduce(addWeeklyInterest(interestRatePerWeek), savings)
}

console.log(calculateTotal(1000.00, 1, 0.02))

Output is 2800.328185448178. You might want to round that for display purposes, but also keep in mind that if accuracy is important, you can't use floating-point numbers.

Upvotes: 1

Related Questions