TM80 TM80 - 1 year ago 68 Question

Using both comma values and period values (

I have three values which need to be sorted from highest to lowset value I use the following code, which works like a charm untill 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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download