Last active
April 6, 2024 04:24
-
-
Save rs77/446c0206d0cbe3e8566f93af6c3ba114 to your computer and use it in GitHub Desktop.
Present Value formula matching Excel and Google Sheets written in Javascript
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
/** | |
* Present 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} pmt - amount paid per period | |
* @param {Number} [fv=0] - future value of the annuity (default 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 pv(rate, nper, pmt, fv = 0, type = 0) { | |
if (rate === 0) return -((pmt * nper) + fv); | |
if (type !== 0 && type !== 1) return null; | |
// Calculate the present value of the annuity (payments). | |
const pvAnnuity = pmt * (1 + rate * type) * (1 - Math.pow(1 + rate, -nper)) / rate; | |
// Calculate the present value of the future value. | |
const pvFV = fv * Math.pow(1 + rate, -nper); | |
// The total present value is the sum of the PV of the annuity and the PV of the future value. | |
// The result is negated to indicate cash outflow. | |
return -(pvAnnuity + pvFV); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment