How to preserve formatting from NumericUpDown to String - vb.net

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

Related

How to increase numeric value present in a string

I'm using this query in vb.net
Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1"))
and I want to increase R|1 to R|2, R|3 and so on using for loop.
I tried it many ways but getting error
string to double is invalid
any help will be appreciated
You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub

Add TextBox strings as numbers

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?

Reduce decimal value in label

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")

Stopping a textbox displaying NaN

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

How do I manipulate the last string of a Richtextbox in Visual Basic

I am trying to take a string in a rich text box and replace them with a different string.
Now how this should work is that if two same characters are entered into the text box
e.g tt the "tt" will be replaced with "Ǿt" , it adds back one of the t's to the replaced string. Only the most recently entered string is manipulated if two same characters are entered .
I read the LAST string that is in the RichTextBox by using this method
Dim laststring As String = RichTextBox1.Text.Split(" ").Last
'hitting space bar breaks the operation so if i enter t t there will be no replacement
this is the replacement method which I use , it works correctly .
if laststring = "tt"
RichTextBox1 .Text = RichTextBox1 .Text.Replace("tt", "Ǿt")
This method is inefficient because i need to check id there are double letters for all letters and if i was to use this method it would tavke up a lot of code .
how can I accomplish this using a shorter method??
You need to put the if then section in a loop.
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
For Each item As String In doubleinstance
If RichTextBox1.Text.EndsWith(item) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" & holdstring)
MsgBox(curstring)
End If
Next item
Here's a bit of code to get you in the right direction...
There are a couple of variations of .Find, but you probably want to look at the .Select method.
With RichTextBox1
.Find("Don")
.SelectedText = "Mr. Awesome"
End With
Here is a way I came up with
Dim holdstring As String
Dim doubleinstance() As String = {"bb", "tt", "uu"} ' array
Dim curstring As String = RichTextBox1.Text.Split(" ").Last
If curstring = doubleinstance(0) And RichTextBox1.Text.EndsWith(doubleinstance(0)) Then
holdstring = RichTextBox1.Text.Split(" ").Last.Length - 1 ' change to subtract 1 character from doubleinstance
RichTextBox1.Text = RichTextBox1.Text.Replace(curstring, "Ǿt" + holdstring)
MsgBox(curstring)
End If
where i have doubleinstance(0) how do i get the if statement to not only check a single index but all of the index from 0 to 2 in this example ?