Search code examples
c#webformspow

Monthly Loan Calculation using Math.Pow


I am attempting to calculate a monthly loan payment using this formula:

Loan Formula

Where L is the loan amount, R is the monthly interest rate, and N is the number of payments.

First I get the input from the web app and do the calculations to get it into the right format for the formula:

double loanAmount = double.Parse(txtLoanAmount.Text) - double.Parse(txtDownPayment.Text);
double interestRate = (double.Parse(txtInterestRate.Text) / 100) / 12;  
double loanPeriod = double.Parse(txtLoanPeriod.SelectedValue) * 12;

Then here is how I currently have the formula written:

Answer = loanAmount * interestRate / 1 - Math.Pow(1 / 1 + interestRate, loanPeriod);

I'm not too overly familiar with the math.pow function (think I've used it once before), so I'm not sure if I am using it properly. If anyone has any suggestions it would be greatly appreciated!


Solution

  • As mentioned in some of the previous comments, operator precedence is going to be an issue in your code.

    From my understanding of your formula, you'll want it to read like this;

    Answer = (loanAmount * interestRate) / (1.0 - Math.Pow(1.0 / 1.0 + interestRate, loanPeriod));
    

    This should get your precedence correct, as well as dealing with any floating point math issues that could arise (note the change from 1 -> 1.0)

    As mentioned by Ron in the comments, you may want to also consider changing from double to decimal for precision.