Can't figure out to properly implement formula to get monthly payment for a mortgage into C#

31 Views Asked by At
static double CalculateMontlyRepayment(double loanAmount, double annualInterestRate, int loanTermYears)
{
    //convert yearly interest into monthly interest.
    double monthlyInterestRate = annualInterestRate / 12.0;

    //Figure out number of monthly payments.
    int loanTermMonths = loanTermYears * 12;

    //The formula to get the monthly payment amount.
    double monthlyPayment = loanAmount * (monthlyInterestRate * Math.Pow(1 + monthlyInterestRate, loanTermMonths)) /
        (Math.Pow(1 + monthlyInterestRate, loanTermMonths) - 1);

    return monthlyPayment;

}

I could do it on a piece of paper but translating it into code is something I'm struggling with. Even tried using AI but it just made it worse.

1

There are 1 best solutions below

0
Yousalc On BEST ANSWER

Interest is supposed to be Percentages. Your formula expressed it as a decimal value.

Change the line below to:

// Convert annual interest rate percentage to decimal and then into monthly interest rate.
double monthlyInterestRate = (annualInterestRate / 100) / 12.0;