Skip to content

Instantly share code, notes, and snippets.

@rs77
Last active April 6, 2024 04:23
Show Gist options
  • Save rs77/e7039903e338f7d3dbcfd71dfe6167d6 to your computer and use it in GitHub Desktop.
Save rs77/e7039903e338f7d3dbcfd71dfe6167d6 to your computer and use it in GitHub Desktop.
Payment amount function for the equivalent PMT() formula seen in Google Sheets and Excel.
/**
* Payment amount formula as seen in Google Sheets/Excel PMT()
* @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} pval - present value
* @param {Number} [fv=0] - future value (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 pmt(rate, nper, pval, fv = 0, type = 0) {
if (rate === 0) return -(pval + fv) / nper;
if (nper === 0) throw new Error('Number of periods cannot be 0');
/** @type {Number} */
const pvFactor = Math.pow(1 + rate, nper);
/** @type {Number} */
let pmt = -rate * (pval * pvFactor + fv) / (pvFactor - 1);
return type === 0 ? pmt : type === 1 ? pmt / (1 + rate) : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment