Skip to content

Instantly share code, notes, and snippets.

@jaimeguaman
Forked from maarten00/pmt.js
Created September 15, 2019 14:43
Show Gist options
  • Save jaimeguaman/9160d51e4e5c16e57ab50212e0c5b43e to your computer and use it in GitHub Desktop.
Save jaimeguaman/9160d51e4e5c16e57ab50212e0c5b43e to your computer and use it in GitHub Desktop.
Excel PMT in PHP and JavaScript
/**
* Copy of Excel's PMT function.
* Credit: http://stackoverflow.com/questions/2094967/excel-pmt-function-in-js
*
* @param rate_per_period The interest rate for the loan.
* @param number_of_payments The total number of payments for the loan in months.
* @param present_value The present value, or the total amount that a series of future payments is worth now;
* Also known as the principal.
* @param future_value The future value, or a cash balance you want to attain after the last payment is made.
* If fv is omitted, it is assumed to be 0 (zero), that is, the future value of a loan is 0.
* @param type Optional, defaults to 0. The number 0 (zero) or 1 and indicates when payments are due.
* 0 = At the end of period
* 1 = At the beginning of the period
* @returns {number}
*/
function pmt(rate_per_period, number_of_payments, present_value, future_value, type){
future_value = typeof future_value !== 'undefined' ? future_value : 0;
type = typeof type !== 'undefined' ? type : 0;
if(rate_per_period != 0.0){
// Interest rate exists
var q = Math.pow(1 + rate_per_period, number_of_payments);
return -(rate_per_period * (future_value + (q * present_value))) / ((-1 + q) * (1 + rate_per_period * (type)));
} else if(number_of_payments != 0.0){
// No interest rate, but number of payments exists
return -(future_value + present_value) / number_of_payments;
}
return 0;
}
/**
* Copy of Excel's PMT function.
* Credit: http://thoughts-of-laszlo.blogspot.nl/2012/08/complete-formula-behind-excels-pmt.html
*
* @param double $interest The interest rate for the loan.
* @param int $num_of_payments The total number of payments for the loan in months.
* @param double $PV The present value, or the total amount that a series of future payments is worth now;
* Also known as the principal.
* @param double $FV The future value, or a cash balance you want to attain after the last payment is made.
* If fv is omitted, it is assumed to be 0 (zero), that is, the future value of a loan is 0.
* @param int $Type Optional, defaults to 0. The number 0 (zero) or 1 and indicates when payments are due.
* 0 = At the end of period
* 1 = At the beginning of the period
*
* @return float
*/
function PMT($interest,$num_of_payments,$PV,$FV = 0.00, $Type = 0){
$xp=pow((1+$interest),$num_of_payments);
return
($PV* $interest*$xp/($xp-1)+$interest/($xp-1)*$FV)*
($Type==0 ? 1 : 1/($interest+1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment