PMT function Payment Type

烈酒焚心 提交于 2020-02-02 15:13:39

问题


Below is my function to calculate loan payment, As like in Excel I need to add another parameter which is payment type.

function PMT (ir, np, pv, fv ) {
 /*
 ir - interest rate per month
 np - number of periods (months)
 pv - present value
 fv - future value (residual value)
 type - 0 or 1 need to implement that
 */
 pmt = ( ir * ( pv * Math.pow ( (ir+1), np ) + fv ) ) / ( ( ir + 1 ) * ( Math.pow ( (ir+1), np) -1 ) );
 return pmt;
}

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.

Can anyone help me to modify the above function with this this PaymentType feature?

http://www.techonthenet.com/excel/formulas/pmt.php


回答1:


I am not sure what you need the PaymentType for, but here what I use for PMT function in C#, it's pure C# PMT function:

public static double PMT(double yearlyInterestRate, int totalNumberOfMonths, double loanAmount)
{
    var rate = (double) yearlyInterestRate / 100 / 12;
    var denominator = Math.Pow((1 + rate), totalNumberOfMonths) - 1;
    return (rate + (rate/denominator)) * loanAmount;
}

Usage:

PMT(7, 360, 120000);
// Result: 798.36
PMT(4.5, 360, 137500.47);
// Result: 696.69
PMT(4.13, 360, 61520);
// Result: 298.33
PMT(6.38, 360, 89200);
// Result: 556.78



回答2:


Using @stack247's answer, if there is a chance the yearly interest rate can be 0% then you might want to add this:

private decimal Pmt(double yearlyInterestRate, int totalNumberOfMonths, double loanAmount)
{
    if (yearlyInterestRate > 0)
    {
        var rate = (double) yearlyInterestRate / 100 / 12;
        var denominator = Math.Pow((1 + rate), totalNumberOfMonths) - 1;
        return new decimal((rate + (rate / denominator)) * loanAmount);
    }
    return totalNumberOfMonths > 0 ? new decimal(loanAmount / totalNumberOfMonths) : 0;
}



回答3:


public static double PMT(double RATE,  int NPER, int PV, long FV, int TYPE)
{
    return -RATE * (FV + PV * Math.Pow(1 + RATE, NPER)) / ((Math.Pow(1 + RATE, NPER) - 1) * (1 + RATE * TYPE));
}


来源:https://stackoverflow.com/questions/5352165/pmt-function-payment-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!