Skip to content

Instantly share code, notes, and snippets.

@ranaroussi
Created September 14, 2023 13:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ranaroussi/05ce40b72baeca33b555f5f7d14800ca to your computer and use it in GitHub Desktop.
Save ranaroussi/05ce40b72baeca33b555f5f7d14800ca to your computer and use it in GitHub Desktop.
Calculate compounded interest with periodic contributions
const calculateCompoundInterest = (P, r, t, n, PMT, PMT_f, toFixed=2) => {
/*
* P = initial principle
* r = interest rate (annual)
* t = duration of invesment
* n = compound events per year (1 = annual, 6 = semi-annual, 3 = quarterly, 12 = monthly, ...)
* PMT = ongoing contibution amount
* PMT_f = contributions per year (1 = annual, 6 = semi-annual, 3 = quarterly, 12 = monthly, ...)
* --->
* I = total investment
* C = compounded interest
* FV = future value
*/
r /= 100; // 8 => 0.08 => 8%
PMT *= parseFloat((PMT_f / n).toFixed(toFixed));
P = parseFloat(P.toFixed(toFixed));
const I = PMT * t + P;
const FV = P * (1 + r / n) ** (n * t) + (PMT * (1 + r / n) ** (n * t) - PMT) / (r / n);
return {
totalInvestment: I,
compoundedInterest: parseFloat((FV - I).toFixed(toFixed)),
futureValue: parseFloat(FV.toFixed(toFixed)),
};
};
// usage:
calculateCompoundInterest(10000, 5, 10, 12, 1000, 12);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment