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
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With