Link to home
Start Free TrialLog in
Avatar of gmahler5th
gmahler5thFlag for United States of America

asked on

Code to calculate monthly payment VB.net

I need to calculate my monthly payment given the loan principal, the percentage, and the terms.  Here are my variables.

      dblPrincipal = CDbl(txtPrincipal.Text)
        dblRate = CDbl(txtRate.Text)
        dblYears = CDbl(txtYears.Text)
ASKER CERTIFIED SOLUTION
Avatar of flavo
flavo
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
woops

dblPayment  = dblPrincipal / ((1 - (1 + dblRateMonth) ^ -dblMonth) / dblRateMonth)
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
maybe i did spend 6 months for nothing.... :-)
Avatar of gmahler5th

ASKER

Ronald, Thank you for sharing.  I like the ease and flexibility of this function.  I sort of hacked it up and put it in my own subroutine, and I am coming up with a monthly payment in the 10s of thousands. Can you look to see that I have used this function correctly?

 'declare your variables here
    Dim dblPrincipal, dblMonth, dblRateMonth, dblRate, dblYears, dblAmount As Double
    Dim PVal, APR, FVal, Payment, TotPmts As Double
    Dim Fmt As String

    Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click

        'assign the values from textboxes to the variables
        PVal = CDbl(txtPrincipal.Text)
        APR = CDbl(txtRate.Text)
        TotPmts = CDbl(txtYears.Text)
        dblMonth = dblYears * 12
        dblRateMonth = dblRate / 12

        'calculate the final amount as principal + interest
        Fmt = "###,###,##0.00"   ' Define money format.
        FVal = 0   ' Usually 0 for a loan.
        Payment = Pmt(APR / 12, TotPmts, -PVal, FVal)

        'put the calculated amount in Payment Amount textbox
        txtAmount.Text = Format(Payment, Fmt)
    End Sub