I need some help creating a mortgage loan calculator that allows the user to input the loan amount, loan years and loan rate and calculates the monthly mortgage payment and displays the amounts due for each month in a datagridview control. The problem is , i cannot seem to loop it using a for loop, i need to use the loop to display all the monthly payments but with my attempt it just repeats the same amounts for every month.Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim loanAmount As Double
Dim loanYears As Integer
Dim loanRate As Double
Dim monthlyPayment As Double
Dim numberofPayments As Integer
Dim monthlyInterest As Double
Dim decimalInterest As Double
Dim interestPaid As Double
Dim newBalance As Double
Dim principle As Double
Dim n As Integer
Dim Pmt As Integer = 1
loanAmount = Val(TextBox1.Text)
loanYears = Val(TextBox2.Text)
loanRate = Val(TextBox3.Text)
decimalInterest = loanRate / 100
numberofPayments = loanYears * 12
monthlyInterest = decimalInterest / 12
Label1.Text = monthlyPayment
For Pmt = 1 To numberofPayments
n = n + 1
If n = numberofPayments + 1 Then
Exit For
End If
monthlyPayment = loanAmount * monthlyInterest / (1 - (1 + monthlyInterest) ^ -numberofPayments)
interestPaid = loanAmount * monthlyInterest
principle = monthlyPayment - interestPaid
newBalance = loanAmount - principle
Me.DataGridView1.Rows.Add(n, Math.Round(monthlyPayment, 2), Math.Round(interestPaid, 2), Math.Round(principle, 2), Math.Round(newBalance, 2))
Next
End Sub
If someone could please help me out , it would be much appreciated.
Thank you
You need loanAmount = loanAmount - principle inside the For, or some other statement that tracks the principle balance and uses it in each iteration. It looks like you're trying to do that with the newBalance variable, but each iteration status over with loanAmount, which never decreases, so the values never change. I would suggest tracing through your math and making sure that your algorithm is actually performing the operations you desire.
Related
I am creating a loan calculator and my loop keeps breaking. I got my stats correct, however I now need to move to a ListBox with more stats.
I can't get this while loop to work I have tried different ways with no avail. This is giving me a headache and I don't know what I am doing wrong.
Public Class Form1
Dim principleamount As Decimal
Dim numberofyears As Decimal
Dim interestrate As Decimal
Dim total As Decimal
Dim paymentnumber As Decimal
Dim currentbalance As Decimal
Dim interestfortheperiod As Decimal
Dim paymentamouhnt As Decimal
Dim newbalance As Decimal
Dim numberofpayments As Decimal
Dim payment As Decimal
Dim interestamount As Decimal
Dim numberofperiods As Integer
Private Sub btncalc_Click(sender As Object, e As EventArgs) Handles btncalc.Click
principleamount = txtprinciple.Text
numberofyears = txtyears.Text
'interest rate
If rba.Checked Then
interestrate = 1.035
End If
If rbb.Checked Then
interestrate = 1.04
End If
If rbc.Checked Then
interestrate = 1.65
End If
If rbc.Checked Then
interestrate = 1.08
End If
If rbd.Checked Then
interestrate = 1.08
End If
If rbe.Checked Then
interestrate = 0.1
End If
'monthly,weekly paymentplan
If rbmonthly.Checked Then
numberofpayments = numberofyears * 12
interestfortheperiod = interestrate / 12
End If
If rbweekly.Checked Then
numberofpayments = numberofyears * 26
interestfortheperiod = interestrate / 26
End If
payment = (principleamount * interestfortheperiod) / (1 - (1 + interestfortheperiod) ^ -numberofpayments)
txtpayment.Text = Format(payment, "#.00")
While principleamount >= 0
paymentnumber += 1
lbpaydetails.Items.Add("Payment Number: " & paymentnumber & " Current Balance: " & & "Interest for the Period: " & & "Payment Amount:" & & "new Balance:" & )
End While
End Sub
End Class
The while loop is going forever, so you need to find a way to decrease 'princlipleamount' in the loop. I am not entirely sure what the code does and how it behaves with your form, so i can not actually solve it.
P.S.
If you are trying to get 'numberofpayments' to be negative, don't put a dash in front of it like this:
payment = (principleamount * interestfortheperiod) / (1 - (1 + interestfortheperiod) ^ -numberofpayments))
But put it in Math.Abs() like this:
payment = (principleamount * interestfortheperiod) / (1 - (1 + interestfortheperiod) ^ Math.Abs(numberofpayments))
Also, you got a bracket missing at the end, i filled it in for you.
Good luck! ;)
I have written this code in visual basic to solve a basic interest calculation. The year end balances are shown in the list box and the final total is show in the label. My problem is that I can not figure out how to round the values in the list box to two decimals. I have tried various things but with no luck so far so I appreciate any help.
Public Class frmNestEgg
Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
' Declare and Initialize the variables
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For Years = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & Years & " Balance " & YrEndAmt)
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub
Private Sub frmNestEgg_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
you could use
Math.Round()
... & Math.Round(YrEndAmt, 2).ToString()
but your code had a flaw: same variable Years for looping and end condition
so change:
For Years = 1 To Years
to:
Dim Years As Integer, year As Integer
For year = 1 To Years
your entire code would then be:
Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnPrincipal.Click
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer, year As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For year = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & year & " Balance " & Math.Round(YrEndAmt, 2).ToString())
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub
So I have this program. It calculates the sale price of an item and displays the tax, subtotal, discount percent, which all works fine. The thing im trying to do is show 3 more textbox that accumulate the subtotal, discount amount, and the average discount.
Everytime I type anything in, the textboxs that are supposed to be accumulating are just displaying what the other boxs say, basically duplicating the boxs
Dim numberOfInvoices As Integer
Dim totalOfInvoices As Decimal
Dim invoiceAverage As Decimal
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim subtotal As Decimal = CDec(txtEnterSubtotal.Text)
Dim discountPercent As Decimal = 0.25D
Dim discountAmount As Decimal = Math.Round(subtotal * discountPercent, 2)
Dim invoiceTotal As Decimal = subtotal - discountAmount
Dim enterSubtotal As Decimal = Val(txtEnterSubtotal.Text)
Dim accumDiscount As Decimal = Val(txtAccumDiscAmount.Text)
Dim avgDiscount As Decimal = Val(txtAccumDiscAmount.Text)
Dim accumSubTotal As Decimal = Val(txtAccumSubtotal.Text)
txtSubtotal.Text = FormatCurrency(subtotal)
txtDiscountPercent.Text = FormatPercent(discountPercent, 1)
txtDiscountAmount.Text = FormatCurrency(discountAmount)
txtTotal.Text = FormatCurrency(invoiceTotal)
numberOfInvoices += 1
totalOfInvoices += invoiceTotal
invoiceAverage = totalOfInvoices / numberOfInvoices
txtNumberOfInvoices.Text = numberOfInvoices.ToString
txtTotalOfInvoices.Text = FormatCurrency(totalOfInvoices)
txtInvoiceAverage.Text = FormatCurrency(invoiceAverage)
'below is where I'm trying to accumulate everything entered....
txtAccumSubtotal.Text = FormatCurrency(accumSubTotal + subtotal)
txtAccumDiscAmount.Text = FormatCurrency(accumDiscount + discountAmount)
If avgDiscount = 0 Then
txtAvgDiscAmount.Text = FormatCurrency(discountAmount)
ElseIf avgDiscount > 0 Then
txtAvgDiscAmount.Text = FormatCurrency(avgDiscount / numberOfInvoices)
End If
txtEnterSubtotal.Text = ""
txtEnterSubtotal.Select()
'This is a comment
End Sub
Ignore my previous post, I was wrong. I found the problem.
VAL() on a percent or currency field will return 0. You have to take the "$" and "%" out of your string to do a VAL().
I am learning VB.net. I am following Charpter 3 of Brian Siler's special edition (2001) using MS VB.net. It looks thing has been changed not too much with VB, but I met a problem in adding table from toolbox.
In the Toolbox (versions from Visual Studio 2012 Express; ASP.net 2012), to build a VB.net project, there are items like TextBox and Table. To build a web app, I can add TextBox, Label, etc and coding them without problems. However, when I add table, there is a problem.
As with Textbox and Label, I rename the table ID (to tblAmortize) first. Then I input the codes from their book, and got an error:
'tblAmortize' is not declared. It may be inaccessible due to its protection level"
As I know, the TextBox item, such as txtPrincipal.Text does not need to be declared when we use it. But it seem this "table" tblAmortize item needs to be declared first, or needs to be build up a link because tblAmortize is located in Form 2 while btnShowDetail_Click is in Form 1. The full code is as following:
Public Class Hello_Web
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim intTerm As Integer 'Term, in years
Dim decPrincipal As Decimal 'Principal amount $
Dim decIntRate As Decimal 'Interst rate %
Dim dblPayment As Double 'Monthly payment $
Dim decMonthInterest As Decimal 'Interest part of monthly payment
Dim decTotalInterest As Decimal = 0 'Total interest paid
Dim decMonthPrincipal As Decimal 'Principal part of monthly pament
Dim decTotalPrincipal As Decimal = 0 'Remaining principal
Dim intMonth As Integer 'Current month
Dim intNumPayments As Integer 'Number of monthly payments
Dim i As Integer 'Temporary loop counter
Dim rowTemp As TableRow 'Temporary row object
Dim celTemp As TableCell 'Temporary cell object
If Not IsPostBack Then 'Evals true first time browser hits the page
'SET Up THE TABLE HEADER ROW
rowTemp = New TableRow()
For i = 0 To 4
celTemp = New TableCell()
rowTemp.Cells.Add(celTemp)
celTemp = Nothing
Next
rowTemp.Cells(0).Text = "Payment"
rowTemp.Cells(1).Text = "Interest"
rowTemp.Cells(2).Text = "Principal"
rowTemp.Cells(3).Text = "Total Int."
rowTemp.Cells(4).Text = "Balance"
rowTemp.Font.Bold = True
tblAmortize.Rows.Add(rowTemp)
'PULL VALUES FROM SESSION VARIABLES
intTerm = Convert.ToInt32(Session("term"))
decPrincipal = Convert.ToDecimal(Session("Principal"))
decIntRate = Convert.ToDecimal(Session("IntRate"))
dblPayment = Convert.ToDecimal(Session("decPayment"))
'CALCULATE AMORTIZATION SCHEDULE
intNumPayments = intTerm * 12
decTotalPrincipal = decPrincipal
For intMonth = 1 To intNumPayments
'Determine Values For the Current Row
decMonthInterest = (decIntRate / 100) / 12 * decTotalPrincipal
decTotalInterest = decTotalInterest + decMonthInterest
decMonthPrincipal = Convert.ToDecimal(dblPayment) - decMonthInterest
If decMonthPrincipal > decPrincipal Then
decMonthPrincipal = decPrincipal
End If
decTotalPrincipal = decTotalPrincipal - decMonthPrincipal
'Add the values to the table
rowTemp = New TableRow()
For i = 0 To 4
celTemp = New TableCell()
rowTemp.Cells.Add(celTemp)
celTemp = Nothing
Next i
rowTemp.Cells(0).Text = intMonth.ToString
rowTemp.Cells(1).Text = Format(decMonthInterest, "$###0.00")
rowTemp.Cells(2).Text = Format(decMonthPrincipal, "$###0.00")
rowTemp.Cells(3).Text = Format(decTotalInterest, "$###0.00")
rowTemp.Cells(4).Text = Format(decTotalPrincipal, "$###0.00")
tblAmortize.Rows.Add(rowTemp)
rowTemp = Nothing
'PrevFormat()
Next intMonth
End If
End Sub
Protected Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decPrincipal As Decimal
Dim decIntRate As Decimal
Dim intTerm As Integer, dblPayment As Double
'Store the principle in the variable decprincipal
'decPrincipal = CDbl(txtPrincipal.Text)
decPrincipal = (txtPrincipal.Text)
'Convert interest rate to its decimal equivalent
' i.e. 12.75 becomes 0.1275
decIntRate = CDbl(txtIntrate.Text) / 100
'Convert annual interest rate to monthly
' by dividing by 12 (months in a year)
decIntRate = decIntRate / 12
'Convert number of years to number of months
' by multiplying by 12 (months in a year)
intTerm = CDbl(txtTerm.Text) * 12
'Calculate and display the monthly payment.
' The format function makes the displayed number look good.
dblPayment = decPrincipal * (decIntRate / (1 - (1 + decIntRate) ^ -intTerm))
txtPayment.Text = Format(dblPayment, "$#,##0.00")
'Add Amortization Schedule
' The Schedule button will be shown only after you click the Calculate Payment LinkButton
btnShowDetail.Visible = True
End Sub
Protected Sub btnShowDetail_Click(sender As Object, e As EventArgs) Handles btnShowDetail.Click
'Storetext box values in session variables
Session.Add("Principal", txtPrincipal.Text)
Session.Add("IntRate", txtIntrate.Text)
Session.Add("Term", txtTerm.Text)
Session.Add("Payment", txtPayment.Text)
'Display the Amortization form
Response.Redirect("frmAmort.aspx")
End Sub
End Class
While you declare the table you must write runat = "Server"
This is the code sample
<Table ID = "tblMyTable" runat = "Server">
.
.
.
</Table>
Now you can use your table in code.
If you can already access the table in Form2's Code and you want it to be accessed in Form1's Code and if you don't know how to do it then here is the solution :
Dim tbl as new Table
tbl = CType(Form1.FindControl("tblMyTable"),Table)
I'm trying to get the program to output the principal paid out to and the interest paid
towards a loan of $5000. No input is take its all been declared already.
Private Sub calButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles calButton.Click
Dim monthlyPayments As Double
Dim bloanTotal As Double = 5000
Dim rate As Double = 0.005
Dim interest As Double
Dim toPrincipal As Double
Dim toInterest As Double
Dim counter As Integer
Do
'calculate the montly payments.
monthlyPayments =
Financial.Pmt(0.06 / 12, 12, 5000)
TextBox1.Text = monthlyPayments.ToString("C2")
counter = counter + 1 'add one to the counter
interest = bloanTotal * rate 'calculate interest rate from payment that will only count as interest
toInterest = monthlyPayments - interest 'amount of monthly payment going towards interest
toPrincipal = monthlyPayments - toInterest ' amount of monthly payment going towards principal
bloanTotal = bloanTotal - toPrincipal 'new balance after deducing principal from begining balance
Label2.Text = toPrincipal.ToString & " " &
toInterest.ToString &
ControlChars.NewLine ' concatinate principal and interest strings and create a new line
If counter = 12 Then 'exit loop once counter has reached 12 and loan amount has reached zero
Exit Do
End If
Loop
End Sub
I believe your problem is that the Financial.Pmt function is returning a negative number. Because this is accounting, you are telling the function you have recieved a 5000 loan (positive number) and you will be making payments (negative number). If you do this
monthlyPayments = Math.Abs(Financial.Pmt(0.06 / 12, 12, 5000))
then your calculations should work out.