Last active
April 6, 2024 04:23
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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