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.
Related
I'm trying to make it so that it counts how many withdrawals a user can have before the bank account's balance is below 0. The inputted numbers are 1000, 60, 50, 300, 800, 53, 2009, and 2015. It's supposed to start with 1000 and subtract 60, then 50, then 300, then 800, which would be 4 withdrawals. Mine doesn't do that and I don't know what I'm doing wrong.
Private Sub btnBankAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBankAccount.Click
Dim inFile As StreamReader = New StreamReader("bank1.txt")
Dim withdrawls As Integer 'count times
Dim money As Integer 'amount of money
Dim difference As Integer = 0 'difference caused by the withdrawls
Do 'read in numbers
money = Val(inFile.ReadLine())
'determine the amount of money
If money > 0 Then
withdrawls = withdrawls + 1
difference = difference - money
End If
Loop Until difference < 0
'display results
Me.lblOutput.Text = withdrawls
End Sub
It seems to me that your code should work if you defined difference as this:
Dim difference As Integer = 0
Now, just to help you with coding style, I'd suggest you write your code like this:
Private Sub btnBankAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBankAccount.Click
Me.lblOutput.Text = GetWithdrawlCount(1000, "bank1.txt")
End Sub
Private Function GetWithdrawlCount(ByVal limit As Decimal, ByVal file As String) As Integer
Dim withdrawls As Integer = 0
Dim difference As Decimal = limit
For Each line In System.IO.File.ReadLines(file)
Dim money = Decimal.Parse(line)
If money > 0 Then
withdrawls = withdrawls + 1
difference = difference - money
End If
If difference < 0 Then
Exit For
End If
Next
Return withdrawls
End Function
I've purposely separated out GetWithdrawlCount so that there are no references to any UI element and that there are no magic numbers or magic strings in the code. Writing it this way makes your code cleaner and easier to test.
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
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.
Am really glad i get someone to help with this , but the problem is am not really good on vb as am very new to it , can anyone please arrange it for me as it need to be then i will see what i can do with it . Then i will be able to start the project
Question is to change states name to 2 Letter and calculate tax rate for them as well.
California retail customers (State code = “CA”) are charged a sales tax on purchases – the California tax rate is 10%. Retail customers from New York (state code = “NY”) and Florida (state code = “FL”) are also taxed at a 5% tax rate.
Below is the code i have so far
Public Class Form1
Public Class State
Public Sub New(ByVal name As String, ByVal abbr As String, ByVal taxPercent As Decimal)
Me.Name = name
Me.Abbreviation = abbr
Me.TaxPercent = taxPercent
End Sub
Public Property Name As String
Public Property Abbreviation As String
Public Property TaxPercent As Decimal
End Class
Const U_P_S_DECIMAL As Decimal = 7D
Const SALES_TAX_RATE_SINGLE As Single = 0.1 '10 Percent Rate
'declare module-level variables
Private TotalQuantityInteger As Integer
Private TotalSalesDecimal As Decimal
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
'5 percent salses tex rate
Const SALES_TEX_RATE_SINGLE As Single = 0.05 '5 percent rate
Dim states As New List(Of State)
states.Add(New State("California", "CA", 10))
states.Add(New State("New York", "NY", 5))
states.Add(New State("Florida", "FL", 5))
For Each state As State In states
Console.WriteLine("State: {0} Abbrevation: {1} Tax: {2}%",
state.Name, state.Abbreviation, state.TaxPercent)
Next
'Declare variables
Dim SubDecimal, SalesTaxDecimal, TotalDueDecimal, TotalCostDecimal, ShippingCostDecimal As Decimal
'Declare variables and convert value from textbox controls to memory
Dim PriceDecimal As Decimal = Decimal.Parse(PriceTextBox.Text, Globalization.NumberStyles.Currency)
Dim QuantityInteger As Integer = Integer.Parse(QuantityTextBox.Text, Globalization.NumberStyles.Number)
'Process - Compute values
'Subtotal = price times the quantity of books
TotalCostDecimal = PriceDecimal * QuantityInteger
'Sales tex = sales tax rate times the subtotal minus discount amount
SalesTaxDecimal = Decimal.Round(Convert.ToDecimal(TotalCostDecimal * SALES_TEX_RATE_SINGLE), 2)
SubDecimal = SalesTaxDecimal + ShippingCostDecimal
'Total due is the subtotal minus discount amount plus sales tex
TotalDueDecimal = TotalCostDecimal + SubDecimal
If UPSRadioButton.Checked Then 'compute the shipping cost
ShippingCostDecimal = U_P_S_DECIMAL * QuantityInteger
End If
'Output - display output formatted as currency
SubtotalTextBox.Text = TotalCostDecimal.ToString("C")
TotalDueTextBox.Text = TotalDueDecimal.ToString("C")
salestaxTextBox.Text = SalesTaxDecimal.ToString("N")
ShippingCostTextBox.Text = ShippingCostDecimal.ToString("N")
'Accumulate total sales and total books sold
TotalQuantityInteger += QuantityInteger
TotalSalesDecimal += TotalDueDecimal
Catch ex As Exception
End Try
End Sub
I have input the code i got on here but i dont know what to do to collect the data from textbox when the state is entered so that tax can be added to it . Any help will be appreciated. Am new to VB so i dont really know how everything works
For Each state As State In states
If state.name = TextBox.text then
'add your code here, you get the tax Rate with state.TaxPercent
'...
exit for
Next
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)