TM80 TM80 - 8 months ago 39 Question

Parsing numbers containing commas or periods

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

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


  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)


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.