Login


C# Payment Calculator

By Jonathan Wood on 6/29/2014
Language: C#
Technology: .NET
Platform: Windows
License: CPOL
Views: 43,626
General Programming » Algorithms » General » C# Payment Calculator

Introduction

Ok, so I'm definitely not much of a finance guy. But I have had a few occassions where I wanted to calculate the monthly payments of a loan for a given term and interest rate. So this seemed like another opportunity to create a nice little C# class that others might find useful.

There is no magic here. Just an equation to calculate the monthly payment. So let's get right to it.

My PaymentCalculator Class

Listing 1 shows my PaymentCalculator class. The class is small and simple, as you can see, with a few properties and only one method.

Listing 1: The PaymentCalculator Class

/// <summary>
/// Class to calculate loan payments
/// </summary>
class PaymentCalculator
{
    private const int MonthsPerYear = 12;

    /// <summary>
    /// The total purchase price of the item being paid for.
    /// </summary>
    public decimal PurchasePrice { get; set; }

    /// <summary>
    /// The total down payment towards the item being purchased.
    /// </summary>
    public decimal DownPayment { get; set; }

    /// <summary>
    /// Gets the total loan amount. This is the purchase price less
    /// any down payment.
    /// </summary>
    public decimal LoanAmount
    {
        get { return (PurchasePrice - DownPayment); }
    }

    /// <summary>
    /// The annual interest rate to be charged on the loan
    /// </summary>
    public double InterestRate { get; set; }

    /// <summary>
    /// The term of the loan in months. This is the number of months
    /// that payments will be made.
    /// </summary>
    public double LoanTermMonths { get; set; }

    /// <summary>
    /// The term of the loan in years. This is the number of years
    /// that payments will be made.
    /// </summary>
    public double LoanTermYears
    {
        get { return LoanTermMonths / MonthsPerYear; }
        set { LoanTermMonths = (value * MonthsPerYear); }
    }

    /// <summary>
    /// Calculates the monthy payment amount based on current
    /// settings.
    /// </summary>
    /// <returns>Returns the monthly payment amount</returns>
    public decimal CalculatePayment()
    {
        decimal payment = 0;

        if (LoanTermMonths > 0)
        {
            if (InterestRate != 0)
            {
                decimal rate = ((InterestRate / MonthsPerYear) / 100);
                decimal factor = (rate + (rate / (Math.Pow(rate + 1, LoanTermMonths) - 1)));
                payment = (LoanAmount * factor);
            }
            else payment = (LoanAmount / (decimal)LoanTermMonths);
        }
        return Math.Round(payment, 2);
    }
}

Using the Class

In order to use this class, you would start by setting the PurchasePrice property. As suggested by the name, this is the purchase price of the item being financed.

Optionally, you can set the DownPayment property. If you do, the loan amount will be calculated by simply subtracting DownPayment from PurchasePrice. The LoanAmount property is a read-only property that returns this calculated value.

Next, you need to set the InterestRate property. This is the annual interest rate that is being charged on the loan. The calculator was designed to also work correctly when there is no interest (InterestRate == 0).

Finally, you'll need to set the term of the loan. Internally, the class stores the term as the number of months. However, you can set this value using either the LoanTermMonths or LoanTermYears properties. The LoanTermYears property will convert the value between years and months.

Once these properties have been set, you can call the CalculatePayment() method. This method returns the amount of your monthly payment.

Below is a simple example of using this class. Listing 2 uses a loop to display the loan details for a 5-year, 6.0%, $50,000.00 loan with varying down payments.

Listing 2: Demonstration of Code that uses the PaymentCalculator Class

void Main()
{
    PaymentCalculator calculator = new PaymentCalculator();
    calculator.PurchasePrice = 50000;
    calculator.InterestRate = 6.0;
    calculator.LoanTermYears = 5;
    for (int i = 0; i <= 10000; i += 1000)
    {
        calculator.DownPayment = i;
        DisplayLoanInformation(calculator);
    }
}

void DisplayLoanInformation(PaymentCalculator calculator)
{
    Console.WriteLine("Purchase Price: {0:C}", calculator.PurchasePrice);
    Console.WriteLine("Down Payment: {0:C}", calculator.DownPayment);
    Console.WriteLine("Loan Amount: {0:C}", calculator.LoanAmount);
    Console.WriteLine("Annual Interest Rate: {0}%", calculator.InterestRate);
    Console.WriteLine("Term: {0} years ({1} months)", calculator.LoanTermYears, calculator.LoanTermMonths);
    Console.WriteLine("Monthly Payment: {0:C}", calculator.CalculatePayment());
    Console.WriteLine();
}

Conclusion

And that's all there is to it. This class could certainly be expanded to handle some variations on the way interest is charged or to add features such as amortization. But it was sufficient for what I needed. And I hope it helps someone else.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.