Parsing numbers containing commas or periods - vb.net

I have three values which need to be sorted from highest to lowest value. I use the following code which works like a charm until I want to use periods "." and commas ",". If I type "1,3" it displays as I like, but if I type "1.3" it changes to 13. My end users need to be able to use both commas and periods.
How can I fix this?
Dim IntArr(2) As Decimal
IntArr(0) = TextBox1.Text
IntArr(1) = TextBox2.Text
IntArr(2) = TextBox3.Text
Array.Sort(IntArr)
Dim highestNum As Decimal
Dim Midelnum As Decimal
Dim lowestNum As Decimal
lowestNum = IntArr(0)
Midelnum = IntArr(1)
highestNum = IntArr(2)
MsgBox("Highest " & highestNum)
MsgBox("lowest " & lowestNum)
MsgBox("middel " & Midelnum)

The problem is that it's based on culture. I say this because if I enter numbers as you described, I get the opposite effect ("1,3" -> "13", etc).
Here's a quick way to change the values to match the current culture.
At the top of your class, put this:
Imports System.Globalization
Then, you can do this:
Dim IntArr(2) As Decimal
Dim nfi As NumberFormatInfo = CultureInfo.CurrentCulture.NumberFormat
Dim sep1 As String = nfi.NumberDecimalSeparator
Dim sep2 As String = If(sep1.Equals("."), ",", ".")
Dim useComma As Boolean = (TextBox1.Text.Contains(",") Or TextBox2.Text.Contains(",") Or TextBox3.Text.Contains(","))
'Replace the separator to match the current culture for parsing
Decimal.TryParse(TextBox1.Text.Replace(sep2, sep1), IntArr(0))
Decimal.TryParse(TextBox2.Text.Replace(sep2, sep1), IntArr(1))
Decimal.TryParse(TextBox3.Text.Replace(sep2, sep1), IntArr(2))
Array.Sort(IntArr)
sep1 = If(useComma, ",", ".")
sep2 = If(useComma, ".", ",")
'Reformat the results to match the user's input
Dim lowestNum As String = IntArr(0).ToString().Replace(sep2, sep1)
Dim middleNum As String = IntArr(1).ToString().Replace(sep2, sep1)
Dim highestNum As String = IntArr(2).ToString().Replace(sep2, sep1)
Dim msg As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
msg = String.Format(msg, highestNum, lowestNum, middleNum)
MessageBox.Show(msg)
Also, since you are using .NET, you may want to skip the VB6 way of doing things. Refer to my example to see what I've used.

You could use the hack of altering the string before saving it:
TextBox.Text.Replace(".",",")
But if you want to show the original input you could have a variable to detect the entered character:
Dim isDot As Boolean = False
Dim number As String = TextBox.Text
If number.Contains(".") Then
isDot = True
End If
And in the end replace it just for purposes of displaying
If isDot Then
number.Replace(",",".")
End If

The accepted answer uses too much unnecessary string manipulation. You can use the CultureInfo object to get what you need:
Sub Main
Dim DecArr(2) As Decimal
'Select the input culture (German in this case)
Dim inputCulture As CultureInfo = CultureInfo.GetCultureInfo("de-DE")
Dim text1 As String = "1,2"
Dim text2 As String = "5,8"
Dim text3 As String = "4,567"
'Use the input culture to parse the strings.
'Side Note: It is best practice to check the return value from TryParse
' to make sure the parsing actually succeeded.
Decimal.TryParse(text1, NumberStyles.Number, inputCulture, DecArr(0))
Decimal.TryParse(text2, NumberStyles.Number, inputCulture, DecArr(1))
Decimal.TryParse(text3, NumberStyles.Number, inputCulture, DecArr(2))
Array.Sort(DecArr)
Dim format As String = "Highest: {0}" & Environment.NewLine & _
"Lowest: {1}" & Environment.NewLine & _
"Middle: {2}"
'Select the output culture (US english in this case)
Dim ouputCulture As CultureInfo = CultureInfo.GetCultureInfo("en-US")
Dim msg As String = String.Format(ouputCulture, format, DecArr(2), DecArr(1), DecArr(0))
Console.WriteLine(msg)
End Sub
This code outputs:
Highest: 5.8
Lowest: 4.567
Middle: 1.2

Related

Using Ms Access VBA, how do I check the value of a variable to see if it has a value other than "', "

I have a variable with a string...and I want to know if it contains any value other than single quote, comma and a space ("', ") I'm using vba in excel.
for example, i have a varible strA = "'test', 'player'"
I want to check to see if strA has any characters other than "', " (single quote, comma and space).
Thanks
Here is a strategy based on Count occurrences of a character in a string
I don't have vba handy, but this should work. The idea is to remove all these characters and see if anything is left. text represents your string that is being tested.
Dim TempS As String
TempS = Replace(text, " " , "")
TempS = Replace(TempS, "," , "")
TempS = Replace(TempS, "'" , "")
and your result is Len(TempS>0)
Another approach is to use recursion by having a base case of false if the string is empty, if the first character is one of the three call ourselves on the rest of the string, or if not the value is true. Here is the code
function hasOtherChars(s As String) As Boolean
hasOtherChars=false
if (len(s)=0) then
exit function
end if
Dim asciiSpace As Integer
asciiSpace = Asc(" ")
Dim asciiComma As Integer
asciiComma= Asc(",")
Dim asciiApostrophe As Integer
asciiApostrophe = Asc("'")
Dim c as Integer
c = Asc(Mid$(s, 1, 1))
if ((c=asciiSpace) or (c=asciiComma) or (c=asciiApostrophe)) then
hasOtherChars = hasOtherChars(Mid$(s,2))
else
hasOtherChars=true
end if
End function
Again I am borrowing from the other thread.

Index and length must refer to a location within the string." & vbCrLf & "Parameter name: length vb.net

Public Sub Main(temp As String)
Dim AccNo As String = temp.Substring(0, 18)
Dim Identifier As String = temp.Substring(36, 46)
Dim Expected As String = temp.Substring(45, 98)
Dim Received As String = temp.Substring(100, 105)
Dim Length As String = temp.Length.ToString
lbLength.Text = Length.ToString
lbAcc.Text = AccNo.ToString
lbIdentifier.Text = Identifier.ToString
lbExpected.Text = Expected.ToString
lbReceived.Text = Received.ToString
End Sub
I'm trying to extract a section from a String line. It's working correctly first two times but then it generates
Index and length must refer to a location within the string." & vbCrLf & "Parameter name: length vb.net"
Please help me to solve this.
At the beginning of your Sub check the length of the temp string.
Dim temp As String = ""
If temp.Length < 205 Then
MessageBox.Show("String is too short to process")
Exit Sub
End If
Substring(StartPosition,length) length is number of characters from starting position.
If you want to do it like Substring(start_position,end_position) end position has to be replaced with (98-45), because end-start=length

Input string was not in a correct format while adding string to integer

I have a code like this :
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
i = (Integer.Parse(strarr(0)) + 1)
mincatval = i
my dr(1) value is L1 i want to add 1,so i want the out put L2,but i am getting error like this :Input string was not in a correct format.
Supposing that strarr(0) is the word "L1" and you want it to become "L2" then you need to isolate the numeric part from the text part and then rebuild the string taking the first part of strarr and the incremented value
Dim mincatval As String
Dim strarr() As String = dr1(0).ToString().Split(New Char() {"-"c})
Dim i As String
Dim itShouldBeAnumber = strarr(0).Substring(1)
if Int32.TryParse(itShouldBeAnumber, i) Then
mincatval = strarr(0).Substring(0,1) & (i + 1)
else
MessageBox.Show("Not a valid number from position 1 of " & strarr(0))
End if
Of course this solution assumes that your string is Always composed of an initial letter followed by a numeric value that could be interpreted as an integer

How could I get the first and last letters from a string?

How can I get my program to take the first and last letters from an entered string?
Example: "I've been told I am a noob!"
Output: "IebntdIaman!"
I tried to use Split with no luck.
Try something like this. since you have a couple of single character words I used a conditional in order to get your desired output. I also am using the String.Split method that removes empty entries in order to prevent a zero length item, then I am taking the result and using the String.Substring Method to parse out your starting and ending chars.
Sub Main()
Dim splitChar As String() = {" "}
Dim example As String = " I've been told I am a noob!"
Dim output As String = ""
Dim result As String() = example.Split(splitChar, StringSplitOptions.RemoveEmptyEntries)
For Each item In result
If item.Length > 1 Then
output += item.Substring(0, 1) & item.Substring(item.Length - 1, 1)
Else
output += item.Substring(0, 1)
End If
Next
Console.WriteLine(output)
Console.ReadLine()
End Sub
This works nicely:
Dim example As String = "I've been told I am a noob!"
Dim result = New String( _
example _
.Split(" "c) _
.SelectMany(Function (w) _
If(w.Count() = 1, _
new Char() { w(0) }, _
New Char() { w.First(), w.Last() })) _
.ToArray())
'IebntdIaman!

How to reverse "This is friday" to "friday is this" in vb.net in Easiest Way

'How to reverse "This is Friday" to "Friday is this" in vb.net in Easiest Way
Dim str As String = txtremarks.Text
Dim arr As New List(Of Char)
arr.AddRange(str.ToCharArray)
arr.Reverse()
Dim a As String = ""
For Each l As Char In arr
a &= l
Next
' I saw on a few forums that to use SPLIT function. Please help
Yes you can use split. You can also use join and the reverse method:
Dim test = "This is Friday"
Dim reversetest = String.Join(" ", test.Split().Reverse)
First you'll want to split your sentence into individual words. This is where you'd use the String.Split method.
Once you have an array containing your individual words, you can reverse that array. Perhaps using Linq's Enumerable.Reverse extension method.
Finally, you can put the words back together into a string. The String.Join method allows you to join the elements of a string array back into a single string.
I'm not a VB programmer, but something like this should work:
Dim str As String = "this is friday"
Dim split As String() = str.Split(" ")
Dim result as String = String.Join(" ", split.Reverse())
Here's a way to do it in 1 line:
Dim reverse As String = "This is friday".Split().Reverse().Aggregate(Function(left, right) String.Join(" ", left, right))
Do note that this has a horrible performance overhead.
Yes, you can Split your String via " " (space) and insert results into array.
Next, read array from the end to start.
Good luck!
Try this...
Dim txt As String = "This is friday"
Dim txtarray() As String = Split(txt.Trim(), " ")
Dim result As String = ""
For x = txtarray.GetUpperBound(0) To 0 Step -1
result += txtarray(x) & " "
Next x
MsgBox(result.Trim())