My question is the bigmac works fine when I press the bigmacadd button and minus button. But when I press the mcdouble add button, I get a bunch of numbers. How can I make it so it shows 2.50 as decimal places?
Public Class Form1
Const bigmac As Decimal = 4D
Const mcdouble As Decimal = 2.25
Dim tax As Decimal
Dim price As Decimal
Dim quantity As Integer
Dim finaltotal As Decimal
Private Sub Btnbigmacadd_Click(sender As Object, e As EventArgs) Handles Btnbigmacadd.Click
quantity = quantity + 1
txtquan.Text = quantity
price += bigmac
txtprice.Text = price
tax = price * 0.15
txttax.Text = tax
finaltotal = price + tax
txtfinaltotal.Text = finaltotal
End Sub
Private Sub btnbigmacminus_Click(sender As Object, e As EventArgs) Handles btnbigmacminus.Click
quantity = quantity - 1
txtquan.Text = quantity
price -= bigmac
txtprice.Text = price
tax = price * 0.15
txttax.Text = tax
finaltotal = price + tax
txtfinaltotal.Text = finaltotal
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
quantity = quantity + 1
txtquan.Text = quantity
price += mcdouble
txtprice.Text = price
tax = price * 0.15
txttax.Text = tax
finaltotal = price + tax
txtfinaltotal.Text = finaltotal
End Sub
End Class
You can round tax to two decimal places using the Math.Round method
tax = Math.Round(price * 0.15D, 2)
txttax.Text = tax.ToString()
finaltotal = price + tax
txtfinaltotal.Text = finaltotal.ToString()
If want to keep the extra decimal places in tax and finaltotal, but show only two decimal places in the text boxes, you can use the ToString("N2") method.
tax = price * 0.15D
txttax.Text = tax.ToString("N2")
finaltotal = price + tax
txtfinaltotal.Text = finaltotal.ToString("N2")
Related
This is what I see in an official tool, and I need to calculate the same end value:
For clarification:
I am given the numbers 95, 3, 5, 19 and 17.15.
I am trying to replicate a math formula in VB.NET in order to achieve the same sum as a government financial tool that I must stay conform with.
The official tool's result and mine differ by 0.1 €, and I don't see what I need to do to achieve the same result.
The official tool states:
A product costs 95.00 € net.
Somebody buys 3 pieces of it.
He gets a discount of 5 % (=4.75 €)
19% VAT is added: 17.15 €
The net price is then 90.25 €
The price is now 270.75 €
The resulting end price is now 322.19 €.
The values that I am given are these:
net price for 1 piece: 95 €
amount: 3
discount per piece: 5%
VAT amount: 19%
VAT: 17.15
First, I calculate the discount like this:
Dim amount As Integer = 3
Dim discount As Double = 5
Dim VAT As Double = 17.15
All result As Decimal
Discount = (amount * discount) / 100 = 4.75
Discounted net price per piece = 95 - 4.75 = 90.25
Discounted net price per piece plus vat = 95 + 17.15 = 107.4
Total price result = discounted net price per piece * amount = 107.4 * 3 = 322.2 €
Is there anything that I'm doing wrong by choosing a wrong operator?
Is it even possible to get the same amount as they do with the information that I am given?
Thank you.
EDIT:
I just realised that you actually did use the correct discounted net price in the calculation below but you just wrote that you didn't, i.e. the result is correct even if the operands aren't.
ORIGINAL:
You do this:
Discounted net price per piece = 95 - 4.75 = 90.25
but then here:
Discounted net price per piece plus vat = 95 + 17.15 = 107.4
you don't use the result of that previous calculation.
Also, even if you did use the discounted price, how does it make sense to add a percentage to a price? Surely you need to calculate that percentage of that price, then add that result to that price. I would think that that line should be this:
Discounted net price per piece plus vat = 90.25 + (90.25 * 17.15 / 100) = 105.7(27875)
According to Decimal Data Type (Visual Basic):
The Decimal data type provides the greatest number of significant
digits for a number...It is particularly suitable for calculations,
such as financial, that require a large number of digits but cannot
tolerate rounding errors.
Try the following:
Create a Windows Forms App (.NET Framework) with the following TextBox names:
TextBoxPrice
TextBoxQuantity
TextBoxDiscountPercentage
TextBoxVATPercentage
TextBoxNetSalesPrice
TextBoxVATAmount
TextBoxGrossSalesPrice
and a Button (name: btnCalculate).
Try the following:
'for testing
Private cultureInfo As System.Globalization.CultureInfo = System.Globalization.CultureInfo.GetCultureInfo("de-DE")
'ToDo: use this one to use the current culture info of the computer
'Private cultureInfo As System.Globalization.CultureInfo = System.Globalization.CultureInfo.CurrentCulture
'get currency symbol
Private currencySymbol As String = cultureInfo.NumberFormat.CurrencySymbol
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim InitialPrice As Decimal = 95
Dim Quantity As Decimal = 3
Dim DiscountPercentage As Decimal = 5
Dim VATPercentage As Decimal = 19
'set value
TextBoxInitialPrice.Text = InitialPrice.ToString("N2", cultureInfo)
TextBoxQuantity.Text = Quantity.ToString("N0", cultureInfo)
TextBoxDiscountPercentage.Text = DiscountPercentage.ToString("N0", cultureInfo)
TextBoxVATPercentage.Text = VATPercentage.ToString("N0", cultureInfo)
End Sub
Private Sub Calculate()
Dim DiscountAmount As Decimal = 0
Dim DiscountPercentage As Decimal = 0
Dim NetPrice As Decimal = 0
Dim InitialPrice As Decimal = 0
Dim Quantity As Decimal = 0
Dim VATAmount As Decimal = 0
Dim VATPercentage As Decimal = 0
Dim GrossSalesPrice As Decimal = 0
'ToDo: Ensure that the user entered valid input. If not, notify the user of invalid input
'convert String to Decimal
Decimal.TryParse(TextBoxInitialPrice.Text, System.Globalization.NumberStyles.Currency, cultureInfo, InitialPrice)
Decimal.TryParse(TextBoxDiscountPercentage.Text, System.Globalization.NumberStyles.Number, cultureInfo, DiscountPercentage)
Decimal.TryParse(TextBoxVATPercentage.Text, System.Globalization.NumberStyles.Number, cultureInfo, VATPercentage)
Decimal.TryParse(TextBoxQuantity.Text, System.Globalization.NumberStyles.Number, cultureInfo, Quantity)
Debug.WriteLine($"A product costs {InitialPrice.ToString("N2", cultureInfo)} {currencySymbol} net.")
Debug.WriteLine($"Somebody buys {Quantity.ToString("N0", cultureInfo)} pieces of it.")
'calculate discount amount
DiscountAmount = Decimal.Multiply(InitialPrice, Decimal.Divide(DiscountPercentage, 100))
Debug.WriteLine($"He gets a discount of {DiscountPercentage.ToString("N0", cultureInfo)}% (={DiscountAmount.ToString("N2", cultureInfo)} {currencySymbol})")
'calculate net price
NetPrice = Decimal.Subtract(InitialPrice, DiscountAmount)
Debug.WriteLine($"The net price is then {NetPrice.ToString("N2", cultureInfo)} {currencySymbol}")
'calculate gross price
Dim NetSalesPrice As Decimal = Decimal.Multiply(NetPrice, Quantity)
Debug.WriteLine($"The price is now {NetSalesPrice.ToString("N2", cultureInfo)} {currencySymbol}")
'set value
TextBoxNetSalesPrice.Text = NetSalesPrice.ToString("N2", cultureInfo)
Debug.WriteLine($"{VATPercentage.ToString("N0", cultureInfo)}% VAT is added to this amount.")
'calculate VAT amount
VATAmount = Decimal.Multiply(NetSalesPrice, Decimal.Divide(VATPercentage, 100))
'set value
TextBoxVATAmount.Text = VATAmount.ToString("N2", cultureInfo)
'calculate grand total (gross sales price)
'GrossSalesPrice = Decimal.Multiply(NetSalesPrice, Decimal.Add(1, Decimal.Divide(VATPercentage, 100)))
GrossSalesPrice = Decimal.Add(NetSalesPrice, VATAmount)
Debug.WriteLine($"The resulting end price is now {GrossSalesPrice.ToString("N2", cultureInfo)} {currencySymbol}")
'set value
TextBoxGrossSalesPrice.Text = GrossSalesPrice.ToString("N2", cultureInfo)
End Sub
Usage:
Calculate()
Update:
From the code above one can extract the following formulas which were created using the information listed beneath The official tool states:
Formulas
DiscountAmount = InitialPrice * (DiscountPercentage / 100.0)
NetPrice = InitialPrice - DiscountAmount
NetPrice = InitialPrice - (DiscountAmount)
NetPrice = InitialPrice - (InitialPrice * (DiscountPercentage / 100.0))
NetSalesPrice = NetPrice * Quantity
VATAmount = NetSalesPrice * (VATPercentage / 100.0)
GrossSalesPrice = NetSalesPrice + VATAmount
Given the following:
NetPrice: 95
Quantity (amount): 3
DiscountPercentage: 5%
VATPercentage: 19%
VATAmount: 17.15
Formula #1: DiscountAmount = InitialPrice * (DiscountPercentage / 100.0)
Formula #2: NetPrice = InitialPrice - (DiscountAmount)
If one substitutes the DiscountAmount formula, in Formula #2, one has:
NetPrice = InitialPrice - (InitialPrice * (DiscountPercentage / 100.0))
Let's insert the information into the formulas:
95 = InitialPrice - (InitialPrice * (5 / 100.0))
95 = InitialPrice - (InitialPrice * 0.05)
Let's change InitialPrice to something that may be more familiar: x
95 = x - (x * 0.05)
95 = 1x - 0.05x
95 = 1.00x - 0.05x
95 = 0.95x
ToDo: Solve for x (InitialPrice).
Formula: NetSalesPrice = NetPrice * Quantity
Insert the information into the formula:
NetSalesPrice = 95 * 3
NetSalesPrice = 285
The information regarding VATAmount and VATPercentage, in the OP, seems to keep changing. Nevertheless, one uses simple algebra to solve for the unknown variable.
Formula: VATAmount = NetSalesPrice * (VATPercentage / 100.0)
Insert the information into the formula:
VATAmount = 285 * (19 / 100.0)
or given VATAmount = 17.15 instead of a VATPercentage:
17.15 = 285 * (VATPercentage / 100.0)
Once again, let's change VATPercentage to something that may be more familiar: x
17.15 = 285 * (x / 100.0)
17.15 = 285x / 100.0
17.15 * 100 = 285x
1715 = 285x
ToDo: Solve for x (VATPercentage).
Resources:
Decimal.Multiply
Decimal.Divide
Decimal.Add
CultureInfo
NumberFormatInfo.CurrencySymbol
Standard numeric format strings
The point of this code is when a user inputs into the textbox how many papers they want printed it would cost $0.30 per paper, if the user purchase more than 499 the price will change to $0.28 per paper etc. But when they check the radiobutton for ink it will cost extra $0.10 per 10 pages printed. I have figure out how to code it but its look messy.
Dim paper As Decimal
Dim price As Decimal
Dim cardstock As Decimal
Dim finalprice As Decimal
Dim remainder As Decimal
Dim extra As Decimal
Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click, btn.Click
paper = Val(Me.txtinput.Text)
If noink.Checked = True Then
If paper <= 499 Then
price = paper * 0.3
Me.lblprice.Text = price
ElseIf paper <= 749 Then
price = paper * 0.28
Me.lblprice.Text = price
ElseIf paper <= 999 Then
price = paper * 0.27
Me.lblprice.Text = price
ElseIf price <= 1000 Then
price = paper * 0.25
Me.lblprice.Text = price
End If
End If
End Sub
Private Sub withink_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles withink.Click
If paper <= 499 Then
price = paper * 0.3
ElseIf paper <= 749 Then
price = paper * 0.28
ElseIf paper <= 999 Then
price = paper * 0.27
ElseIf price <= 1000 Then
price = paper * 0.25
End If
remainder = paper Mod 10
cardstock = paper - remainder
extra = cardstock / 100
finalprice = extra + price
Me.lblprice.Text = finalprice
End Sub
first, try use just as checkbox instead of a radiobutton and check that checkstate, so you only need one control
second, I like the idea of having to check the textinput directly and don't use a button to check like E.Solicito suggested but thats up to your preferences
third, here's the code
Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.click
If txtinput.Text.Length = 0 Then
paper = 0
Else
paper = Val(Me.txtinput.Text)
End If
Check_Ink()
End Sub
Private Sub Checkbox_Status(sender As Object, e As EventArgs) Handles chb_withink.CheckedChanged
Check_Ink()
End Sub
Private Sub Check_Ink()
Select Case paper
Case paper <= 499
price = paper * 0.3
Case paper <= 749
price = paper * 0.28
Case paper <= 999
price = paper * 0.27
Case Else
price = paper * 0.25
End Select
If chb_withink.Checked Then
remainder = paper Mod 10
cardstock = paper - remainder
extra = cardstock / 100
price += extra
End If
Me.lblprice.Text = price
End Sub
Try this
Private Sub txtinput_TextChanged(sender As Object, e As EventArgs) Handles txtinput.TextChanged
If txtinput.Text = Nothing Then
txtinput.Text = 0
End If
paper = Val(Me.txtinput.Text)
Check_Ink()
End Sub
Private Sub RadioButton_Status(sender As Object, e As EventArgs) Handles noink.CheckedChanged, withink.CheckedChanged
Check_Ink()
End Sub
Public Sub Check_Ink()
If noink.Checked = True Then
If paper <= 499 Then
price = paper * 0.3
Me.lblprice.Text = price
ElseIf paper <= 749 Then
price = paper * 0.28
Me.lblprice.Text = price
ElseIf paper <= 999 Then
price = paper * 0.27
Me.lblprice.Text = price
ElseIf price <= 1000 Then
price = paper * 0.25
Me.lblprice.Text = price
End If
Else
If paper <= 499 Then
price = paper * 0.3
ElseIf paper <= 749 Then
price = paper * 0.28
ElseIf paper <= 999 Then
price = paper * 0.27
ElseIf price <= 1000 Then
price = paper * 0.25
End If
remainder = paper Mod 10
cardstock = paper - remainder
extra = cardstock / 100
finalprice = extra + price
Me.lblprice.Text = finalprice
End If
End Sub
I'm trying to add labels together in a list box and they add together just fine with val(). However when I add currency signs to the label val() stops working.
This is the code that works without using any currency signs:
'Sales Tax
Public Const intSALESTAX_Rate As Decimal = 0.06
'Shipping cost
Public Const Shipping_Rate As Integer = 2
'Audio Books
Public Const History_of_Scotland_Audio As Decimal = 14.5
Public Const Calculus_One_Day_Audio As Decimal = 29.95
Public Const Science_Body_Language_Audio As Decimal = 12.95
Public Const Relaxation_Techniques_Audio As Decimal = 11.5
'Print Books
Public Const Did_Your_Way_Print As Decimal = 11.95
Public Const History_Of_Scotland_Print As Decimal = 14.5
Public Const Calculus_One_Day_Print As Decimal = 29.95
Public Const Feel_The_Stress_Print As Decimal = 18.5
Private Sub btnAddtoCartAudioBook_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddtoCartAudioBook.Click
Dim value As Decimal
Dim shipping As Integer
Dim tax As Decimal
Dim grand_total As Decimal
Dim ShoppingCart As New Form1()
If lstAudioBooks.SelectedIndex = -1 Then
MessageBox.Show("Select an audio book.")
Return
End If
Form1.lstShoppingCart.Items.Add(lstAudioBooks.SelectedItem.ToString())
Select Case lstAudioBooks.SelectedItem.ToString()
Case "Learn Calculus in One Day (Audio)"
Debug.WriteLine("Learn Calculus in One Day (Audio)")
value = Val(Form1.lblSubtotal.Text) + Form1.Calculus_One_Day_Audio
Form1.lblSubtotal.Text = FormatNumber(value, 2)
Case "Relaxation Techniques (Audio)"
Debug.WriteLine("Relaxation Techniques (Audio)")
value = Val(Form1.lblSubtotal.Text) + Form1.Relaxation_Techniques_Audio
Form1.lblSubtotal.Text = FormatNumber(value, 2)
Case "The History of Scotland (Audio)"
Debug.WriteLine("The History of Scotland (Audio)")
value = Val(Form1.lblSubtotal.Text) + Form1.History_of_Scotland_Audio
Form1.lblSubtotal.Text = FormatNumber(value, 2)
Case "The Science of Body Language (Audio)"
Debug.WriteLine("The Science of Body Language (Audio)")
value = Val(Form1.lblSubtotal.Text) + Form1.Science_Body_Language_Audio
Form1.lblSubtotal.Text = FormatNumber(value, 2)
Case Else
Debug.WriteLine("No Value")
End Select
'shipping calculations
shipping = Val(Form1.lblShipping.Text) + Form1.Shipping_Rate
Form1.lblShipping.Text = FormatNumber(shipping, 2)
'tax calculations
tax = value * Form1.intSALESTAX_Rate
Form1.lblTax.Text = FormatNumber(tax, 2)
'Sub total calculation
grand_total = FormatNumber(value + shipping + tax, 2)
Form1.lblTotal.Text = FormatNumber(grand_total, 2)
Return
End Sub
However if I add a dollar sign to the label val() stops working
value = Val(Form1.lblSubtotal.Text) + Form1.Calculus_One_Day_Audio
Form1.lblSubtotal.Text = "$" + FormatNumber(value, 2)
How can I run calculations with the labels if the value contains a dollar sign?
one method would be to remove the dollar sign before calling the val() function. For example lets say the numbers are in this format:
$45, $1, $456
dim strTemp as string
strTemp = strings.right(strings.len(Form1.lblSubtotal.Text)-1)
Value = Val(strTemp)
if its in the format:
$ 45, $ 1, $ 456
dim strTemp as string
strTemp = strings.right(strings.len(Form1.lblSubtotal.Text)-2)
Value = Val(strTemp)
I don't deal with VB. I am helping my mother with her homework and just cant think straight anymore on what to do with this statement.
Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
Dim intPackA As Integer = 0
Dim intPackB As Integer = 0
Dim intPackC As Integer = 0
Dim SavingsPriceB As Decimal = 0.0
Dim SavingsPriceC As Decimal = 0.0
Dim TotalPrice As Decimal = 0.0
lblTotal.Text = String.Empty
If radPackA.Checked Then
TotalPrice = 9.95
lblTotal.Text = TotalPrice
If Integer.TryParse(txtHours.Text, intPackA) Then
If intPackA > 10 Then
TotalPrice = TotalPrice + ((intPackA - 10) * 2)
lblTotal.Text = TotalPrice
End If
End If
If chkSavings.Checked Then
SavingsPriceB = 14.95 + ((intPackB - 20) * 1)
SavingsPriceC = 19.95
If TotalPrice < SavingsPriceB And TotalPrice < SavingsPriceC Then
lblTotal.Text = TotalPrice & ", no savings with Package B or C"
End If
End If
ElseIf radPackB.Checked Then
TotalPrice = 14.95
lblTotal.Text = TotalPrice
If Integer.TryParse(txtHours.Text, intPackB) Then
If intPackB > 20 Then
TotalPrice = TotalPrice + ((intPackB - 20) * 1)
lblTotal.Text = TotalPrice
End If
End If
If chkSavings.Checked Then
End If
ElseIf radPackC.Checked Then
TotalPrice = 19.95
lblTotal.Text = TotalPrice
End If
If chkNonprofit.Checked Then
TotalPrice = Format((TotalPrice - ((TotalPrice / 100) * 20)), ".00")
lblTotal.Text = TotalPrice & ControlChars.CrLf & "Non-Profit Organization discount applied"
End If
End Sub
It's the If chkSavings.Checked that's giving me problem.
This is the program as designed. There is a label bellow the packages that displays the total.
When the Potential Savings is checked, it should also display the amount you could save if you use a different package.
So if I put Package A, 5 hours, 20% discount it should say $7.96, no savings with Package B or C. For Package A, 25 hours it should say $39.95, save $20.00 with Package B, and save $20.00 with Package C
The code I have does not print it even the first part.
Package A and less then 10 hours = $9.95, every additional hour is $2.00 more
Package B and less then 20 hours = $14.95, every additional hour is $1.00 more
Package C with unlimited hours is = $19.95
So My question is, what am I doing wrong in my code or how could I achieve what I am looking for.
So I have a pretty simple UDF written in visual basic for use in excel. It calculates your approx. taxes. Lets say I use it as such:
=Taxes(I23-I18,I24-I20,"Married")
If I type this in it works great. Now if I save the sheet and restart excel the cell now says #VALUE! If I select the formula and hit enter once again it recalculates it fine. What am I doing wrong? Application.Volatile shouldn't be needed but I was trying ideas...
Private Type TaxBracket
Perc As Double
Floor As Currency
Limit As Currency
End Type
Public Function Taxes(gross1 As Currency, gross2 As Currency, filingStatus As String) As Currency
Application.Volatile True
Dim brackets(6) As TaxBracket
Dim stdDeduction As Currency
Dim ssTaxRate As Double
Dim medicareTaxRate As Double
Dim Tax As Double
stdDeduction = 5700
ssTaxRoof = 106800
ssTaxRate = 0.062
medicareTaxRate = 0.0145
Tax = medicareTaxRate * (gross1 + gross2)
Tax = Tax + IIf(gross1 < ssTaxRoof, ssTaxRate * gross1, ssTaxRate * ssTaxRoof)
Tax = Tax + IIf(gross2 < ssTaxRoof, ssTaxRate * gross2, ssTaxRate * ssTaxRoof)
brackets(0).Perc = 0.1
brackets(1).Perc = 0.15
brackets(2).Perc = 0.25
brackets(3).Perc = 0.28
brackets(4).Perc = 0.33
brackets(5).Perc = 0.35
If filingStatus = "Single" Then
brackets(0).Floor = 0
brackets(1).Floor = 8375
brackets(2).Floor = 34000
brackets(3).Floor = 82400
brackets(4).Floor = 171850
brackets(5).Floor = 373650
brackets(0).Limit = 8375
brackets(1).Limit = 34000
brackets(2).Limit = 82400
brackets(3).Limit = 171850
brackets(4).Limit = 373650
brackets(5).Limit = 1000000000
Tax = Tax + incomeTaxes(gross1, brackets, stdDeduction) + incomeTaxes(gross2, brackets, stdDeduction)
ElseIf filingStatus = "Married" Then
brackets(0).Floor = 0
brackets(1).Floor = 16750
brackets(2).Floor = 68000
brackets(3).Floor = 137300
brackets(4).Floor = 209250
brackets(5).Floor = 373650
brackets(0).Limit = 16750
brackets(1).Limit = 68000
brackets(2).Limit = 137300
brackets(3).Limit = 209250
brackets(4).Limit = 373650
brackets(5).Limit = 1000000000
Tax = Tax + incomeTaxes(gross1 + gross2, brackets, stdDeduction * 2)
Else
Taxes = "N/A"
Return
End If
Taxes = Tax
End Function
Private Function incomeTaxes(gross As Currency, brackets() As TaxBracket, deduction As Currency) As Currency
Dim Tax As Double
Dim taxable As Double
Tax = 0
taxable = gross - deduction
For i = 0 To 5
If taxable > brackets(i).Limit Then
Tax = Tax + (WorksheetFunction.Min(taxable, brackets(i).Limit) - brackets(i).Floor) * brackets(i).Perc
Else
If taxable > brackets(i).Floor Then
Tax = Tax + (taxable - brackets(i).Floor) * brackets(i).Perc
Else
'tax = tax
End If
End If
Next i
incomeTaxes = Tax
End Function
Your UDF's look OK, apart from using Currency data types (probably should be using doubles or variants since that is what Excel uses).
The usual reason for getting #Value with a UDF is that one of the input arguments cannot be converted to the correct type. If your input cells do not contain numeric values when the workbook opens you would get #Value. This might be caused by calculation sequence problems resulting in one of the upstream precedent cells being uncalculated the first time the function is called. Try declaring the input parameters as variant rather than currency and add some temporary debug.print statements to show the input parameters in the Immediate window.