Visual basic not adding number together from textbox's? - vb.net

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

Related

I HAVE BEEN OVER THIS GOD KNOWS HOW MANY TIMES, WHAT IS WRONG WITH IT? (TICKET MACHINE) NO ERRORS ON VS), i think the top few line may not work

I have been looking over this for the last couple of days and personally I am not to keen on VB, the tab is loading up but I am not getting an answer?
Private Sub Button1_click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Age As Double
Dim seatgrading As Double
Dim Cardaddition As Single
Dim Memberdiscount As Single
Dim installments As Double
Dim totalcost As Double
Dim eachpayment As Integer
Dim total As Single
Dim price As Single
Dim Subtotal As Single
Age = CBOAge.Text
If RBFootball.Checked = True And Age = rbChild.Checked Then
price = 275
ElseIf RBFootball.Checked = True And Age = rbAdult.Checked Then
price = 450
ElseIf RBFootball.Checked = True And Age = rbOAP.Checked Then
price = 295
End If
If RBRugby.Checked = True And Age = rbChild.Checked Then
price = 85
ElseIf RBRugby.Checked = True And Age = rbAdult.Checked Then
price = 175
ElseIf RBRugby.Checked = True And Age = rbOAP.Checked Then
price = 105
End If
' Seat Grades
If RBG1.Checked = True Then
seatgrading = 150
ElseIf RBG2.Checked = True Then
seatgrading = 120
ElseIf RBG3.Checked = True Then
seatgrading = 87.5
End If
total = price + seatgrading
MemberDiscount = installments
If RBBronze.Checked = True Then
MemberDiscount = total * 0.08
ElseIf RBSilver.Checked = True Then
MemberDiscount = total * 0.09
ElseIf RBGold.Checked = True Then
`Cardaddition` = total * 0.025
End If
If RBCard.Checked = True Then
Cardaddition = Subtotal = 0.025
End If
If installments = True Then
installments = total * 0.0375
total = totalcost + installments
eachpayment = totalcost / 12
For count = 1 To 12
installments = installments & "payment" & "is" & Format(eachpayment, "currency") & vbCrLf
Next
End If
total = Subtotal - MemberDiscount + Cardaddition
total = Format(totalcost, "currency")
End Sub
This answer is perhaps more of a way to show you how to get to the code you need than a complete answer.
When dealing with money, it is best to use the Decimal type instead of Single or Double, otherwise the pennies can go wrong after a calculation or two.
You can have an If statement inside another If statement, which can sometimes make for less typing and/or easier reading.
I can't see a need for the age variable because there are already radiobuttons for child/adult/OAP.
The way of calculating the final total price was not clear to me, so I moved some things around into what may or may not be the correct order.
Perhaps the installments variable is meant to be a checkbox for if the payments are going to be taken monthly - I assumed that is the case.
I couldn't see where the results are being presented to the user, so I used MessageBox.Show - I'm sure you will be able to adapt it to how you want to show the total etc.
Private Sub Button1_click(sender As Object, e As EventArgs) Handles Button1.Click
' What I think the variable types are:
' Dim rbChild, rbAdult, rbOAP As New RadioButton
' Dim rbFootball, rbRugby As New RadioButton
' Dim rbG1, rbG2, rbG3 As New RadioButton
' Dim rbBronze, rbSilver, rbGold As New RadioButton
' Dim cbCard As New CheckBox
' Dim cbInstallments As New CheckBox
Dim price As Decimal
If rbFootball.Checked Then
If rbChild.Checked Then
price = 275
ElseIf rbAdult.Checked Then
price = 450
ElseIf rbOAP.Checked Then
price = 295
End If
End If
If rbRugby.Checked Then
If rbChild.Checked Then
price = 85
ElseIf rbAdult.Checked Then
price = 175
ElseIf rbOAP.Checked Then
price = 105
End If
End If
Dim seatgrading As Decimal
If rbG1.Checked Then
seatgrading = 150
ElseIf rbG2.Checked Then
seatgrading = 120
ElseIf rbG3.Checked Then
seatgrading = 87.5D
End If
Dim subtotal As Decimal = price + seatgrading
Dim memberDiscount As Decimal
If rbBronze.Checked Then
memberDiscount = subtotal * 0.08D
ElseIf rbSilver.Checked Then
memberDiscount = subtotal * 0.09D
ElseIf rbGold.Checked Then
memberDiscount = subtotal * 0.025D
End If
Dim cardSurcharge As Decimal
If cbCard.Checked Then
cardSurcharge = subtotal * 0.025D
End If
Dim total As Decimal = subtotal - memberDiscount + cardSurcharge
If cbInstallments.Checked Then
Dim installmentSurcharge = total * 0.0375D
total = total + installmentSurcharge
Dim eachpayment As Decimal = total / 12
MessageBox.Show("Monthly payment is " & eachpayment.ToString("C"))
End If
MessageBox.Show("Total payment is " & total.ToString("C"))
End Sub

Dynamic Arrays in VB

Struggling student here... I've been asked to find the min, max and mid-point value. However, I cannot figure this out; arrays/data storage is 3 chapters away. So, I'm hoping someone could help me out with this conundrum.
-I need to get the data from an individual element within an array in decimal. Any ideas? I've largely been unsuccessful with the 'array.getvalue' method & with the 'array.min' methods.
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 minimum, maximum, middle, i As Decimal
Dim array(1) As Decimal
Dim midpoint As Integer
txtSubtotal.Text = FormatCurrency(subtotal)
txtDiscountPercent.Text = FormatPercent(discountPercent, 1)
txtDiscountAmount.Text = FormatCurrency(discountAmount)
txtTotal.Text = FormatCurrency(invoiceTotal)
numberOfInvoices += 1
totalOfInvoices += invoiceTotal
invoiceAverage = totalOfInvoices / numberOfInvoices
For i = 0 To numberOfInvoices - 1
array(i) = i
ReDim Preserve array(0 To numberOfInvoices - 1)
Next i
If numberOfInvoices = 1 Then
minimum = totalOfInvoices
middle = totalOfInvoices
maximum = totalOfInvoices
End If
If numberOfInvoices > 1 Then
midpoint = numberOfInvoices / 2
middle = array.GetValue(midpoint)
For Each i In array
If i < UBound(array) - 1 Then If array(i) > array(i + 1) Then maximum = array(i)
If i < UBound(array) - 1 Then If array(i) < array(i + 1) Then minimum = array(i)
Next i
End If
txtLargestInvoice.Text = maximum.ToString
txtSmallestInvoice.Text = minimum.ToString
txtMidPoint.Text = middle.ToString
txtNumberOfInvoices.Text = numberOfInvoices.ToString
txtTotalOfInvoices.Text = FormatCurrency(totalOfInvoices)
txtInvoiceAverage.Text = FormatCurrency(invoiceAverage)
txtEnterSubtotal.Text = ""
txtEnterSubtotal.Select()
End Sub
Private Sub BtnClearTotals_Click(sender As Object,
e As EventArgs) Handles btnClearTotals.Click
numberOfInvoices = 0
totalOfInvoices = 0
invoiceAverage = 0
txtNumberOfInvoices.Text = ""
txtTotalOfInvoices.Text = ""
txtInvoiceAverage.Text = ""
txtEnterSubtotal.Select()
End Sub
Private Sub BtnExit_Click(sender As Object,
e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Comments and explanations in-line
Private Sub OPCode2()
'You can declare and initialize an array in one line
Dim arr() As Double = {13.5, 18.0, 6.2, 11.8, 13.6}
'Just check intellisense for a list of methods and properties of arrays
Dim myAverage As Double = arr.Average()
Dim myMin As Double = arr.Min
Dim myMax As Double = arr.Max
Dim myMedian As Double
'The original array is lost when .Sort is applied
Array.Sort(arr)
Dim myLength As Integer = arr.Length
'If the lenght of the array is even you could also average
'the middle two values And return that number which
'may not be a value in the original array
myMedian = arr(CInt(myLength / 2)) 'returns the higher of the middle two if length is even
'or the actual middle value in the sorted array
MessageBox.Show($" The Average value is {myAverage}
The Maximum value is {myMax}
The Minimum value is {myMin}
The Median value is {myMedian}")
End Sub

Cannot figure out calculation

I need to make a phone bill program that would allow the user to calculate their phone bill. They would enter their minutes, texts and data allowance as well as how much they've used.
Each extra minute is 30p, each extra text is 10p and data used over the limit is £10.00, all added to the final cost.
The problem is that I cannot get the program to calculate the cost of each minute, I guess that after finding out how the minutes are calculated I will be able to do the same for the texts and the data.
Thanks for the help, much appreciated.
This is the problem
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btn1TotalCost_Click(sender As Object, e As EventArgs) Handles btn1TotalCost.Click
Dim MinutesAllowed As Integer
Dim MinutesUsed As Integer
Dim TextsAllowed As Integer
Dim TextsUsed As Integer
Dim DataAllowed As Integer
Dim DataUsed As Integer
Dim MinutesTotalCost As Double
Dim TextsTotalCost As Double
Dim DataTotalCost As Double
Dim MonthlyCost As Double
Dim TotalCost As Double
MinutesAllowed = Val(txtBoxMinutesAllowed.Text)
MinutesUsed = Val(txtBoxMinutesUsed.Text)
TextsAllowed = Val(txtBoxTextsAllowed.Text)
TextsUsed = Val(txtBoxTextsUsed.Text)
DataAllowed = Val(txtBoxDataAllowed.Text)
DataUsed = Val(txtBoxDataUsed.Text)
MinutesTotalCost = Val(txtBoxTotalCost.Text)
TextsTotalCost = Val(txtBoxTotalCost.Text)
DataTotalCost = Val(txtBoxTotalCost.Text)
TotalCost = Val(txtBoxTotalCost.Text)
'Minutes
MinutesAllowed = Integer.Parse(txtBoxMinutesAllowed.Text)
MinutesUsed = Integer.Parse(txtBoxMinutesUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If MinutesAllowed >= MinutesUsed Then
MinutesTotalCost = 0
Else
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
End If
txtBoxTotalCost.Text = CType(MinutesTotalCost + MonthlyCost, String)
'Texts
TextsAllowed = Integer.Parse(txtBoxTextsAllowed.Text)
TextsUsed = Integer.Parse(txtBoxTextsUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If TextsAllowed >= TextsUsed Then
TextsTotalCost = 0
Else
TextsTotalCost = (TextsUsed - TextsAllowed) * 0.15
End If
txtBoxTotalCost.Text = CType(TextsTotalCost + MonthlyCost, String)
'Data
DataAllowed = Integer.Parse(txtBoxDataAllowed.Text)
DataUsed = Integer.Parse(txtBoxDataUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If DataAllowed >= DataUsed Then
DataTotalCost = 0
Else
DataTotalCost = (DataUsed - DataAllowed) + 10.0
End If
txtBoxTotalCost.Text = CType(DataTotalCost + MonthlyCost, String)
End Sub
End Class
MinutesTotalCost = MinutesUsed - MinutesAllowed * 0.3
Multiplication and division operators have precedence over the addition and subtraction operators.
You need to add brackets to the calculation.
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
You also overwrite the result of the calculation here:
MinutesTotalCost = txtBoxTotalCost.Text
Edit: Working code for just the minutes
Dim MinutesAllowed As Integer
Dim MinutesUsed As Integer
Dim MinutesTotalCost As Double
Dim MonthlyCost As Double
MinutesAllowed = Integer.Parse(txtBoxMinutesAllowed.Text)
MinutesUsed = Integer.Parse(txtBoxMinutesUsed.Text)
MonthlyCost = Val(txtBoxMonthlyCost.Text)
If MinutesAllowed >= MinutesUsed Then
MinutesTotalCost = 0
Else
MinutesTotalCost = (MinutesUsed - MinutesAllowed) * 0.3
End If
txtBoxTotalCost.Text = CType(MinutesTotalCost + MonthlyCost, String)
Val() returns a double so you need to use Integer.Parse() for int.
Double needs to be converted to string for the textbox.
Edit 2:
Since MonthlyCostdoesn't change you need the line
MonthlyCost = Val(txtBoxMonthlyCost.Text)
only once at the beginning.
You are always overwriting the value of txtBoxTotalCost. Just make a single calculation with all costs i.e.
txtBoxTotalCost.Text = CType(MinutesTotalCost + TextsTotalCost + DataTotalCost + MonthlyCost, String)

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 Hospital Stay Calculator

So I am writing this program that should return the total cost of a hospital stay. Everything appears to be working fine, except the most important part...the total cost of the hospital stay. I have looked everywhere for a possible solution, to no avail. The program continues to return $0.00 no matter what I do. No error messages, just $0.00 every single time. I realize I have not included exception handling as of yet, which I will do once I get the kinks worked out. Any idea what my issue is here? Thanks in advance!
Const decRatePerDay As Decimal = 350.0
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim NumOfDays As Integer
Dim MedCharges As Decimal
Dim SurgicalCharges As Decimal
Dim LabFees As Decimal
Dim RehabCharges As Decimal
Dim TotalCharges As Decimal
NumOfDays = CDec(txtNumOfDays.Text)
MedCharges = CDec(txtMedCharges.Text)
SurgicalCharges = CDec(txtSurgicalCharges.Text)
LabFees = CDec(txtLabFees.Text)
RehabCharges = CDec(txtLabFees.Text)
lblCalTotalCost.Text = TotalCharges.ToString("c")
End Sub
Function CalcStayCharges(NumOfDays As Integer) As Decimal
Dim decCostOfStay As Decimal
NumOfDays = CDec(txtNumOfDays.ToString)
decCostOfStay = NumOfDays * decRatePerDay
Return decCostOfStay
End Function
Function CalcMiscCharges(MedCharges As Decimal, SurgicalCharges As Decimal, LabFees As Decimal, RehabCharges As Decimal) As Decimal
Dim TotalMisc As Decimal
MedCharges = CDec(txtMedCharges.ToString)
SurgicalCharges = CDec(txtSurgicalCharges.ToString)
LabFees = CDec(txtLabFees.ToString)
RehabCharges = CDec(txtLabFees.ToString)
TotalMisc = MedCharges + SurgicalCharges + LabFees + RehabCharges
Return TotalMisc
End Function
Function CalcTotalCharges(CostOfStay As Decimal, TotalMisc As Decimal) As Decimal
Dim TotalCharges As Decimal
TotalCharges = CostOfStay + TotalMisc
lblCalTotalCost.Text = TotalCharges.ToString("c")
Return TotalCharges
End Function
You never set the value of TotalCharges and you never call your functions to calculate the total charges.
Change
lblCalTotalCost.Text = TotalCharges.ToString("c")
To
lblCalTotalCost.Text = CalcTotalCharges(CalcStayCharges(NumOfDays), _
CalcMiscCharges(MedCharges, SurgicalCharges, LabFees, RehabCharges)) _
.ToString("C")