Skip to content

Instantly share code, notes, and snippets.

@rs77
Last active April 6, 2024 04:22
Show Gist options
  • Save rs77/c91bd5d15f0f99ab682fb6ad92bd75df to your computer and use it in GitHub Desktop.
Save rs77/c91bd5d15f0f99ab682fb6ad92bd75df to your computer and use it in GitHub Desktop.
Future Value formulas as seen in Excel in Google Sheets written in Javascript format.
/**
* Future Value formula as detailed in Google Sheets/Excel
* @param {Number} rate - as a decimal not as a percentage per period
* @param {Number} nper - total number of periods remaining, needs to be the same period as rate
* @param {Number} [pymt=0] - amount paid per period (optional is pval is not 0, otherwise default is 0)
* @param {Number} [pval=0] - present value of the annuity (optional if pymt is 0, otherwise default is 0)
* @param {Number} [type=0] - is payment in arrears, paid at the end of each period, (0) or in advance, paid at the start of each period (1) (default is 0 = arrears)
* @returns {Number}
*/
function fv(rate, nper, pymt = 0, pval = 0, type = 0) {
if (pymt === 0 && pval === 0) return 0;
if (pymt === 0) return -pval * Math.pow(1 + rate, nper);
if (rate === 0) return -pval - (pymt * nper);
if (pval !== 0 && pymt === 0) pymt -= -pmt(rate, nper, pval, 0, type);
// Calculate the future value of the initial amount
const fvOfPVal = pval * Math.pow(1 + rate, nper);
// Calculate the future value of the periodic payments
let fvOfPymts = pymt * (Math.pow(1 + rate, nper) - 1) / rate;
// Adjust for payment at the beginning of the period
fvOfPymts *= type === 1 ? (1 + rate) : 1;
// The future value is the sum of the FV of the lump sum and the FV of the payments
// Because these represent outflows, we use a negative sign
return -(fvOfPVal + fvOfPymts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment