I have a label that shows too many decimal values.
For example,
textbox1 = 22
textbox2 = 7
label1 = textbox2/textbox1
I want label1 turn to 31.8 but it always turn to 31.8181811818181818881
I have already tried:
Dim label1 As String
label1 = (CInt(Me.textbox2.Text) / CInt(Me.textbox1.Text)) * 100
Format(label1, "0.00")
Form3.label1.Text = label1 + " %"
Acc. to your comment:
#KashishArora yes
I will do it in a very very simple way!
Explanation
We will first simply divide Textbox1 with Textbox2 and store the value in a label and then declare an integer a as label1.text (it isn't necessary to do it in variable, you can do directly). Then we will use the Math.Round control and specify the number of decimals we want (1 or 2).
And then finally, store the value of a back to Label1.
Code And Example
Label1.Text = Val(TextBox2.Text) / Val(TextBox1.Text)
Dim a As Double = Label1.Text
a = Math.Round(a, 2) '2 is number of decimal places
Label1.Text = a
'All the things you want to do with this.
I hope it works perfectly!
Use String.Format()...
Dim label1 As String
label1 = (CInt(Me.textbox2.Text) / CInt(Me.textbox1.Text)) * 100
label1 = String.Format("{0:0.0}", label1)
Form3.label1.Text = label1 & " %"
Just use the combination of substring and lastindexof
label1 = textbox2/textbox1
Dim labelText As String = label1.Text
labelText = labelText.Substring(0, labelText.LastIndexOf(".") +2) + "%"
You're all making this more complex than it is. Decimal.ToString has an overload where you can pass a standard or custom numeric format string.
In your case on should use the F{n} format specifier where {n} is the precision specifier indicating the desired number of decimal places.
label1.Text = (Decimal.Parse(textBox1.Text) / Decimal.Parse(textbox2.Text)).ToString("F2")
Related
I am trying to create a simple counter that increases when the button is clicked.
What I would like is when the counter is clicked it displays "01", "02" etc.
I can create it already with "1", "2", but I would like to have a leading zero.
I have searched and found I can do this by converting the label to a string, but I cant seem to get the value to count?
If I change "count.text = counter" to "count.text = cot" it will display "01", but wont count. I'm guessing this is due to the fact its only displaying what is currently in the string but not increasing the value?
If I could get any guidance that would be great!
Many thanks!
Dim counter As Integer = 1
Dim cot As String = String.Format("{0:00}", counter)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
counter = cot + 1
count.Text = counter
End Sub
PadLeft is the key.
Dim number as Integer = 12
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 12
number = 2
Console.WriteLine(number.ToString().PadLeft(2, "0")). ' prints 02
The problem is, that you don't update your formatted number properly. It's only initialized a single time.
To increment the counter, use counter += 1 or counter = counter + 1 first. This will add 1 to the current value of the integer variable. Then modify the text of your Label by calling that formatting code again: count.Text = String.Format("{0:00}", counter).
This should get you started...
it converts the string into an integer. increments the number, converts it back into a string and then checks for a leading 0, if not found it adds it.
I will let you convert it into your button click for practise, as it should help you have a good understanding of the conversion between types :)
Sub string_counter()
Dim string_counter As String
string_counter = "00"
For x = 0 To 10
Debug.Print string_counter
string_counter = Int(string_counter) + 1
string_counter = Str(string_counter)
If Left(Trim(string_counter), 1) <> "0" Then
string_counter = "0" + Trim(string_counter)
End If
Next x
End Sub
I want to calculate each line: it's like first line 123*1.616 and the second line 213*1.616, and display each total.
Every number entred in the kilogram textbox will mutiply 1.616 and then show the result in the kati label.
Here is my code:
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Enter
For Each digit In (TextBox1.Text)
total1 = Val(digit) * 1.616
Label9.Text = total1
Next
Label9.Text = total1
End sub
Please help me find some solution or explanation to achieve the output.
This should work
Private FACTOR As Decimal = 1.616
Private SEPARATOR As String = Environment.NewLine
Private Sub b1_Click(sender As Object, e As EventArgs) Handles b1.Click
Label9.Text = TextBox1.Text.
Split({SEPARATOR}, StringSplitOptions.RemoveEmptyEntries).
Select(Function(s1) $"{Decimal.Parse(s1) * FACTOR:0.00#}").
Aggregate(Function(s1, s2) $"{s1}{SEPARATOR}{s2}")
End Sub
Here are the functions in the LINQ
Split makes an array out of each line in the TextBox using SEPARATOR as the delimiter
Select transforms the elements into their value times FACTOR
Aggregate puts the elements back together into a SEPERATOR delimited string
Why didn't your original code work?
You were iterating over each char in the text, and multiplying the char by a float (Option Strict On, as suggested in the comments would have prevented that).
Then in each iteration, you do (simplified) Label9.Text = Val(digit) * 1.616 which overwrites the Label every time.
If you were to step through in debug (also suggested in comments), you would see the Label becoming 1x1.616=1.616, 2x1.616=3.232, 3x1.616=4.848, etc. The result was the very last character in your TextBox, '3', times 1.161 = 4.848. Obviously, this was not what you wanted. You needed to instead iterate over each entire number. The multiline TextBox separates each line with a new line. So we iterate over each line instead.
you can use split string by vbCrLf
Sub main()
Dim multilinetext As String =
"10
20
30
40
50
60"
Dim number_array = multilinetext.Split(vbCrLf)
Dim output As Integer = 0
For Each i In number_array
output += i
Next
Stop
End Sub
I'm making a counter that updates when the calculate button is pressed, but when I press it it add it like:
11111
where the answer should be 5.
Const tax = 1.05
Dim capPrice = 4.0
Dim espPrice = 2.5
Dim latPrice = 3.5
Dim icedPrice = 3.0
'keeping here teporarily
Dim takeAway = True
If (takeAway = True) Then
capCounter.text = capCounter.text + capAmount.text
espCounter.Text = espCounter.Text + espAmount.Text
latCounter.Text = latCounter.Text + latAmount.Text
icedCounter.Text = icedCounter.Text + icedAmount.Text
What you observe is string concatenation because a TextBox stores strings. You have to convert it to a number, for example with Int32.Parse, then you can sum the values:
Dim capCount As Int32
Dim capAmount as Int32
Dim validCapCount = Int32.TryParse(capCounter.Text, capCount)
Dim validCapAmount = Int32.TryParse(capAmount.Text, capAmount)
If validCapCount AndAlso validCapAmount Then
capCounter.Text = (capCount + capAmount).ToString()
End If
' do the same with the other values ...
This is because the Property Text of a control is a String.
If you want to perform your addition, you must convert those texts to a Integer first :
capCounter.text = (CType(capCounter.text, Integer) + CType(capAmount.text, Integer)).ToString()
(This if you are sure it will only be integers contained in the texts)
If you will use it for numbers only and allow user imput I will recommend you to use a numericUpDown and not a textboxt.
Then you can use the Value property of the numericupdown and it will return a numeric value, not a String.
However, if you need it to be a textbox, use CType as SuperPeanut sugested or TryParse as Tim sugested
Most of the other comments explain most of it, but have you tried using a different type of control to display the information, perhaps a NumericUpDownControl?
I have got a text box that displays the result of two others multiplied together, before anything is in-putted the box displays NaN, is there a way to have it display "0" or even remain empty before anything multiplied.
Dim thick1 As Double
Dim tb8 As Double
Dim result As Double
thick1 = Val(thickness1.Text)
tb8 = Val(TextBox8.Text)
result = thick1 / tb8
TextBox30.Text = FormatNumber(result, 3)
^ the above code is what I am using for the text box.
Try something like this:
Dim result As Double
Dim thick1 As Double = CDbl(thickness1.Text)
Dim tb8 As Double = CDbl(TextBox8.Text)
If IsNumeric(thick1) AndAlso IsNumeric(tb8) AndAlso tb8 <> 0 Then
result = thick1 / tb8
TextBox30.Text = result.ToString("G3")
End If
Another way, try this:
TextBox30.Text = FormatNumber(result, 3).Tostring("n0")
I think it should displays a 0 even if number is not present (like a NaN string)
MSDN: The Numeric ("N") Format Specifier
If not, then try this else:
TextBox30.Text = FormatNumber(result, 3).ToString("0")
"0" Zero placeholder
Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.
MSDN: Custom Numeric Format Strings
This would appear to be code in an event or form load that it is automatically running. If the textboxes do not yet have values, then result = thick1 / tb8 will result in Nan (not a Number) because you cannot divide by zero.
Again, assuming an event or something:
If tb8 = 0 then
Exit Sub
else
result = thick1 / tb8
TextBox30.Text = result.ToString("G3")
End if
In addition to dumping VAL for TryParse, consider turning Option Explicit on
My form contains several NumericUpDown controls. These controls show different amount of decimal places.
Later in my code I put the different NumericUpDown.Value's in a string array arrStr() like so:
arrStr(1) = NumericUpDown1.Value
arrStr(2) = NumericUpDown2.Value
arrStr(3) = NumericUpDown3.Value
Then I print the array with the File.WriteAllLines function to a text file.
If for example NumericUpDown1.Value = 1.00, NumericUpDown2.Value = 2.30 and NumericUpDown3.Value = 2.124 the file has the following values in it:
1
2.3
2.124
I would like to see:
1.00
2.30
2.124
I have tried Format which works, but that formatting method is not convenient as the amount of decimal places is already set for each NumericUpDown. It would be annoying to do the work again, but now with Format.
You could use String.Format to force two decimal places:
Dim value As Double = 2.3
Dim formatted = String.Format("{0:f2}", value) ' 2.30 '
Standard Numeric Format Strings
Edit: If you're array is large and you want to avoid:
arrStr(1) = String.Format("{0:f2}", NumericUpDown1.Value) up to arrStr(86) = String.Format("{0:f2}", NumericUpDown86.Value)
You can use LINQ to create the array. Assuming that your NumericUpDown controls are all in a GroupBox called NumericGroupBox. You can "inject" the correct number of decimal places:
Dim arrStr() As String =
(From n In NumericGroupBox.Controls.OfType(Of NumericUpDown)()
Select String.Format("{0:f" & n.DecimalPlaces & "}", n.Value)).ToArray()
and here's a version that searches all TabPages of your TabControl(as commented):
Dim allNumerics = From tp In Me.TabControl1.TabPages.Cast(Of TabPage)()
From n In tp.Controls.OfType(Of NumericUpDown)()
Select String.Format("{0:f" & n.DecimalPlaces & "}", n.Value)
Dim arrStr As String() = allNumerics.ToArray()