Loan calculator using while loop - vb.net

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! ;)

Related

How to I make the values in the list box round to two decimal places with this visual basic code

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

Displaying Input into textbox

I am trying to display a calculation into a TextBox, but having trouble with getting it to show. I want it to show once all input fields are true.
Public Class VehicleAudit
Private Sub Calculate()
Dim validMiles As Boolean = False
Dim validPercent As Boolean = False
Dim validAvg As Boolean = False
Dim inputtedMiles As Double
Dim inputtedPercent As Double
Dim inputtedAvgCost As Double
Dim servTruck As Integer
Try
inputtedMiles = Double.Parse(txtMilesDriven.Text)
inputtedPercent = Double.Parse(txtPercent.Text)
inputtedAvgCost = Double.Parse(txtAvgCost.Text)
Catch ex As FormatException
MessageBox.Show("Please enter all values and try again")
Return
End Try
Dim cal As String = FormatCurrency(Convert.ToString(inputtedAvgCost * inputtedMiles * (1.0 + inputtedPercent))) + " dollars."
ValidateBoxes(inputtedMiles, 0, 10000, "Miles must range from 0-10000.", validMiles)
ValidateBoxes(inputtedPercent, 0.1, 0.5, "Please enter percent from .10 to .50", validPercent)
ValidateBoxes(inputtedAvgCost, 0.25, 0.75, " Please enter Average cost from .25 to .75", validAvg)
If (validAvg And validMiles And validPercent) Then
Dim totalCost As Double
If boxVehicleSelect.SelectedIndex = 9 Then
servTruck = inputtedMiles / 100 'this way we lose precision using the integer, so values below 100s are dropped.
totalCost = servTruck * 15.46
Else
totalCost = inputtedAvgCost * inputtedMiles * (1.0 + inputtedPercent)
End If
End If
End Sub
Private Sub txtTotalCost_TextChanged(ByVal Calculate As String, e As EventArgs) Handles txtTotalCost.TextChanged
End Sub
You appear to already have a block that runs when all three values are "valid". Simply output that value at the bottom of it:
If (validAvg And validMiles And validPercent) Then
Dim totalCost As Double
If boxVehicleSelect.SelectedIndex = 9 Then
servTruck = inputtedMiles / 100 'this way we lose precision using the integer, so values below 100s are dropped.
totalCost = servTruck * 15.46
Else
totalCost = inputtedAvgCost * inputtedMiles * (1.0 + inputtedPercent)
End If
' Output the computed "totalCost" some where.
' Here I'm using a Textbox called "txtTotalCost":
txtTotalCost.Text = totalCost.ToString()
End If
Edit...
Also call your Calculate() method whenever one of your textboxes changes:
Private Sub TextChanged(sender As Object, e As EventArgs) Handles txtMilesDriven.TextChanged, txtAvgCost.TextChanged, txtPercent.TextChanged
Calculate()
End Sub
Note how all three textboxes are listed after the handles keyword.

Mortgage loan calculator

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.

Visual basic not adding number together from textbox's?

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().

Invalid values not breaking, results not being shown

My VB.NET program is giving me two errors:
It does not break when I enter a negative value or 0.
It does not show me the total values.
Can anyone help me with this problem?
Enter deposit amount: 300
Another (y or n)? y
Enter deposit amount: -1
Amount cannot be zero or negative.
My Code:
Module Module1
Sub Main()
Dim userResponse As Char
Dim depositAmount As Decimal
Dim totalDeposits As Decimal
Dim depositCount As Integer
Dim averageDeposit As Decimal
depositCount = 0
totalDeposits = 0
While Not (userResponse = "n")
Console.WriteLine("Enter Desposit Amount:")
If (depositAmount < 0 And depositAmount = 0) Then
Console.WriteLine("Amount cannot be zero or negative.")
Else
depositAmount = Console.ReadLine()
Console.WriteLine("Another (y or n)?")
userResponse = Console.ReadLine()
totalDeposits = totalDeposits + depositAmount
depositCount = depositCount + 1
averageDeposit = totalDeposits / depositCount
End If
End While
Console.WriteLine(" Total deposits: " + totalDeposits.ToString)
Console.WriteLine(" Number of deposits: " + depositCount.ToString)
Console.WriteLine("Average deposit: " + averageDeposit.ToString)
End Sub
End Module
You may be able to try: If (depositAmount < 0 or depositAmount = 0) From what I see the value cannot be negative and zero at the same time.
It does not break when I enter a negative value or 0.
It does not show me the total values.
You're coding without your options turned on and trying to implicitly convert string to Decimal. Also you're checking depositamount before the user enters it.
try something like this:
Module Module1
Sub Main()
Dim userResponse As Char
Dim depositAmount As Double
Dim totalDeposits As Double
Dim depositCount As Integer
Dim averageDeposit As Double
depositCount = 0
totalDeposits = 0
While Not (userResponse = "n")
Console.WriteLine("Enter Desposit Amount:")
'Attempt to convert readline to double. if it's successful GoodResponse
'is true and depositamount has the value entered, otherwise it's 0
Dim GoodResponse As Boolean = Double.TryParse(Console.Readline(), depositAmount)
If Not GoodResponse OrElse depositAmount <=0 Then
depositAmount = 0
Console.WriteLine("Amount must be a number and cannot be zero or negative.")
End If
Console.WriteLine("Another (y or n)?")
userResponse = Console.ReadLine()
totalDeposits = totalDeposits + depositAmount
depositCount = depositCount + 1
averageDeposit = totalDeposits / depositCount
End If
End While