Excel PMT function in JS

前端 未结 3 657
-上瘾入骨i
-上瘾入骨i 2021-02-06 04:07

I found i little snipet on internet, about PMT calculate.

function PMT(i, n, p) {
 return i * p * Math.pow((1 + i), n) / (1 - Math.pow((1 + i), n));
}
function C         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 04:33

    This question's been dead for over a year, but I recently needed to do the same thing. Here's what I came up with:

    function pmt(rate_per_period, number_of_payments, present_value, future_value, type){
        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;
    }
    

    type needs to be 1 or 0, same as Excel's. The rate_per_period needs to be a decimal (eg: 0.25, not 25%).

    An example:

    /* Example: */
    var interest    = 0.07,     // Annual interest
        years       = 5,        // Lifetime of loan (in years)
        present     = 10000,    // Present value of loan
        future      = 20000,    // Future value of loan
        beginning   = 1;        // Calculated at start of each period
    
    var payment = -pmt(interest / 12,   // Annual interest into months
                       years * 12,      // Total months for life of loan
                       present,
                       future,
                       beginning);
    

    And the payment for the example period (month) is ~$474.60.

    Note the negation of the result, as the amount is a dedection - ie: costs you $474 - the result is a negative value. Were the result to be a credit, the result would be a positive. Generally you'll want to keep it as a negative/positive, but if you were displaying it in a format like Total Debt: $XYZ, you'd want to convert it to a positive.

提交回复
热议问题