I need to calculate and get a total amount for a unit with multiple calculation conditions. If I enter an amount in a textbox and press enter the second textbox should display a total amount for the below conditions.
(if unit = 450)
0-100 = 3.00 // 101-200 = 5.00 // 201-300 = 7.00 // over 300 = 10.00
if i press enter after entering the unit as 450 second textbox should display total as 2000.00. I am new to vb.net can anyone help me to do this
(for first 100 => 300.00 / second 100 => 500.00 / third 100 => 700.00 / fourth 100 => 500.00 altogether totally 2000.00)
Here is a simple console application to illustrate the process. The idea is to go from the highest range to the lowest and always check if we have to take items from the current range.
Class AmountLimit
Public Property AmountLowerBound As Integer
Public Property Value As Double
Public Sub New(amountLowerBound As Integer, value As Double)
Me.AmountLowerBound = amountLowerBound
Me.Value = value
End Sub
End Class
Sub Main()
'Specify the values for each range. The first number is the lower bound for the range
Dim amountLimits As New List(Of AmountLimit)
amountLimits.Add(New AmountLimit(0, 3))
amountLimits.Add(New AmountLimit(100, 5))
amountLimits.Add(New AmountLimit(200, 7))
amountLimits.Add(New AmountLimit(300, 10))
Console.Write("Enter the total amount: ")
Dim totalAmount = Integer.Parse(Console.ReadLine())
Dim finalValue As Double = 0
For i As Integer = amountLimits.Count - 1 To 0 Step -1
'Check if our total amount is greater than the current lower bound
Dim currentRange = amountLimits(i)
If (totalAmount > currentRange.AmountLowerBound) Then
finalValue += (totalAmount - currentRange.AmountLowerBound) * currentRange.Value
totalAmount = currentRange.AmountLowerBound
End If
Next
Console.WriteLine(finalValue)
End Sub
Related
My code:
Imports System
Module Program
Sub Main(args As String())
Dim Price As Integer
Dim Qty As Integer
Dim Total As Integer
Console.Write("Enter the product unit price. ")
Price = Console.ReadLine()
Console.Write("Enter the product quantity. ")
Qty = Console.ReadLine()
Total = Price * Qty
If (Qty > 99) And (Qty < 150) Then
Console.WriteLine("You did not qualify for a discount. Your total is: " + Total.ToString)
End If
If (100 < Qty > 149) Then
Console.WriteLine("You qualified for a 10% discount! Your total is: " + (Total * 1.1).ToString)
End If
If (Qty > 149) And (Qty < 200) Then
Console.WriteLine("You qualified for a 15% discount! Your total is: " + (Total * 1.15).ToString)
End If
If (Qty > 199) Then
Console.WriteLine("You qualified for a 20% discount! Your total is: " + (Total * 1.2).ToString)
End If
End Sub
End Module
I can run it to input the values but crash when the math component is executed. Any ideas on how to fix this silly little program?
This isn't a thing:
If (100 < Qty > 149) Then
If needs to look more like this:
If 100 <= Qty AndAlso Qty < 150 Then
The first condition should also just be If Qty < 100 Then
Worse, Qty is a STRING. For cultural/internationalization reasons, converting between strings and numbers is one of the slowest and most error-prone operations you can do within a single computer. It's something to minimize. Therefore you should parse the Qty and Price variables into actual Integer and Decimal variables once right after you read them from the user. Failure to do so makes the code seem amateurish.
Finally, rather than a bunch of If/Else conditions I'd put the data in an ordered map and take the first match:
Imports System
Imports System.Linq
Imports System.ValueTuple ' No longer needed on recent versions of VS
Module Program
Sub Main(args As String())
Console.Write("Enter the product unit price. ")
Dim Price As Decimal = Decimal.Parse(Console.ReadLine())
Console.Write("Enter the product quantity. ")
Dim Qty As Integer = Integer.Parse(Console.ReadLine())
Dim Total As Decimal = Price * Qty
Dim discount As Decimal = GetDiscount(Qty)
Dim discountMessage As String = "You did not qualify for a discount."
If discount > 0.0D Then
discountMessage = $"You qualified for a {discount:P0} discount!"
Total *= (1.0D - discount)
End If
Console.WriteLine($"{discountMessage} Your total is: {Total:C2}")
End Sub
Public Function GetDiscount(Qty As Integer) As Decimal
Dim discountMap() As (Integer, Decimal) = {
(200, 0.20D),
(150, 0.15D),
(100, 0.10D),
(Integer.MinValue, 0.00D)
}
Return discountMap.First(Function(m) m.Item1 <= Qty).Item2
End Function
End Module
If some of this code looks strange to you, it relies on Tuples, a lambda expression, and string interpolation; all three techniques are good tricks to add to your programming repertoire.
Here is an example of the For loop that I'm trying to run where lstCost is my ListBox that is formed by selecting options from two other ListBoxes and calculating a total for those option to create an item total and totalCost is the variable where I'm trying to save the total of all list items.
Dim totalCost As Integer
For x As Integer = 0 To lstCost.Items.Count - 1
totalCost += Val(lstCost.Items.Item(x))
Next
txtTotalCost.Text = totalCost.ToString
For some reason, I end up with a 0 as my total in my txtTotalCost TextBox. Can anybody think of any reason why?
Dim totalCost As Double = 0
For x As Integer = 0 To lstCost.Items.Count - 1
totalCost += DirectCast(lstCost.Items.Item(x).ToString.trim,Double)
Next
txtTotalCost.Text = totalCost.ToString
depending on your values in listbox you can change it to Decimal if required
Calculating PreTax, Tax, and Total amounts based on items in list box. Here's how it looks currently when executed:
https://drive.google.com/open?id=0B3W0gSES_-fNMmdnU1VTSzR2dFk
Here is the code I have so far:
'load ListBox with test data:
For dblPrices As Double = 1 To 4
lstPrices.Items.Add(dblPrices.ToString("c2"))
Next dblPrices
'calculate pretax total:
Dim dblPretaxTotal As Double = 0
Dim dblSelectedPrice As Double
For intTax As Integer = 0 To lstPrices.Items.Count - 1
lstPrices.SelectedIndex = 0
Dim strPrice As String
strPrice = Convert.ToString(lstPrices.SelectedItem)
Double.TryParse(strPrice, dblSelectedPrice)
dblPretaxTotal = dblSelectedPrice
Next intTax
I only have it programmed to calc and display the PreTax Total currently. It should show $10.00. Any suggestions are welcome.
I think your problem is the failed double conversion.
try this:
dblPretaxTotal += Double.Parse(strPrice, NumberStyles.Currency) * taxRate;
instead of Double.TryParse() without checking for the result. NumberStyles.Currency and a taxrate was also missing.
I have a DataGridView which contains 1000 data points. I have successfully calculated the min, max, and average of the values in my DataGridView, but now I want to get the min, max, and average values only from a certain range. For example, data in 101 to 200 or 201 to 300 .
For i As Integer = 0 To dataGridView1.Rows.Count() - 1 Step +1
sum_tmp = sum_tmp + dataGridView1.Rows(i).Cells(2).Value
If i = 0 Then
max_tmp = dataGridView1.Rows(i).Cells(2).Value
min_tmp = dataGridView1.Rows(i).Cells(2).Value
End If
If max_tmp < dataGridView1.Rows(i).Cells(2).Value Then
max_tmp = dataGridView1.Rows(i).Cells(2).Value
End If
If min_tmp > dataGridView1.Rows(i).Cells(2).Value Then
min_tmp = dataGridView1.Rows(i).Cells(2).Value
End If
Next
avg_tmp = sum_tmp / dataGridView1.Rows.Count()
Above is my code to get the value. I have tried using integer variable that changed by selecting combobox but still always get 0 value on min. Sadly it shows the right value on the average. How is it possibly wrong?
You can use a LINQ expression to get an enumerable collection of the values you want to process, then use built-in functions to get the max, min, and average
Define a struct which will hold the resulting calculations
Private Structure ResultsStruct
Public Min As Single
Public Max As Single
Public Average As Single
Public Sum As Single
End Structure
This function returns the struct when called. Pass in the first row index and last row index.
Private Function getResults(firstRow As Integer, lastRow As Integer) As ResultsStruct
Dim skipRows = firstRow - 1
Dim takeRows = lastRow - skipRows
Dim values = DataGridView1.Rows.
OfType(Of DataGridViewRow)().
Select(Of Single)(Function(r) Single.Parse(r.Cells(0).Value.ToString())).
Skip(skipRows).
Take(takeRows)
Dim max = values.Max()
Dim min = values.Min()
Dim avg = values.Average()
Dim result As New ResultsStruct() With {.Max = values.Max(),
.Min = values.Min(),
.Average = values.Average(),
.Sum = values.Sum()}
Return result
End Function
How it's called
Dim result = getResults(firstRow:=201, lastRow:=300)
MessageBox.Show(String.Format("Max: {0}, Min: {1}, Avg: {2}, Sum: {3}",
result.Max, result.Min, result.Average, result.Sum))
Replace 201 and 300 in the example with the range you are interested in, whether it is from the user selecting the grid or some other means of input.
I have 3 column Qty,Price and Amount and i need to compute the amount per line using DataGridView, what are the possible events I may use?
i assumed that Quantity is Cell 0, Price is Cell 1, and Amount is Cell 2
For i As Integer = 0 To DataGridView1.RowCount - 1
Dim xQty as Double = CDBL(DataGridView1.Rows(i).Cells(0).Value)
Dim xPrc as Double = CDBL(DataGridView1.Rows(i).Cells(1).Value)
DataGridView1.Rows(i).Cells(2).Value = xQty * xPrc
Next