PMT function in Javascript

The easiest way to understand the impact of the Type parameter is to try the following values: Annual Interest = 12%, # of Months = 1, Present Value = 100

When Type=0 (the default), the PMT() function will yield 101

When Type=1, the PMT() function will yield 100

With Type=0, the interest is computed for 1 month because the payment is assumed to be at the end of the month. For Type=1, the interest is computed for 0 months because the payment is at the beginning of the month.


this is my version of PMT function after some googling:

function PMT(ir, np, pv, fv, type) {
    /*
     * ir   - interest rate per month
     * np   - number of periods (months)
     * pv   - present value
     * fv   - future value
     * type - when the payments are due:
     *        0: end of the period, e.g. end of month (default)
     *        1: beginning of period
     */
    var pmt, pvif;

    fv || (fv = 0);
    type || (type = 0);

    if (ir === 0)
        return -(pv + fv)/np;

    pvif = Math.pow(1 + ir, np);
    pmt = - ir * (pv * pvif + fv) / (pvif - 1);

    if (type === 1)
        pmt /= (1 + ir);

    return pmt;
}

Example What is the monthly payment needed to pay off a $200,000 loan in 15 years at an annual interest rate of 7.5%?

ir = 0.075 / 12
np = 15 * 12
pv = 200000
pmt = PMT(ir, np, pv).toFixed(2) = -1854.02
payoff = pmt * np = -333723.6

here in my PMT version

PMT: function(rate, nperiod, pv, fv, type) {
    if (!fv) fv = 0;
    if (!type) type = 0;

    if (rate == 0) return -(pv + fv)/nperiod;

    var pvif = Math.pow(1 + rate, nperiod);
    var pmt = rate / (pvif - 1) * -(pv * pvif + fv);

    if (type == 1) {
        pmt /= (1 + rate);
    };

    return pmt;
},

//// Call the PMT

 var result = PMT(6.5/1200 , 30*12 , 65000 , 0 , 0);
 console.log(result);
 //// result : -410.8442152704279

/// Other as well IPMT and PPMT

 IPMT: function(pv, pmt, rate, per) {
    var tmp = Math.pow(1 + rate, per);
    return 0 - (pv * tmp * rate + pmt * (tmp - 1));
},

PPMT: function(rate, per, nper, pv, fv, type) {
    if (per < 1 || (per >= nper + 1)) return null;
    var pmt = this.PMT(rate, nper, pv, fv, type);
    var ipmt = this.IPMT(pv, pmt, rate, per - 1);
    return pmt - ipmt;
},