January 29, 2008

A quick and dirty way to know current locale's decimal separator

Those who work with locales, where decimal separator is not a "." might have ran into issues doing calculations in script. From what I've seen, developers usually hard-code replacements for their local decimal separator to be substituted with a ".", which is expected by the script.

Let's assume you are parsing an XML file and you need to do some calculations:

   1:  'Let's assume your locale's decimal separator is a comma
   2:  strSomeValue = "3.1415" 'the value retrived from xml
   3:  'Now let's assume you need to multiply it by 2
   4:  result = strSomeValue * 2 'result is 62830

The problem is that script does not recognize "." as a decimal separator in a string if your locale's separator is different. Certainly, you can replace "." in your strings with your decimal separator (e.g. ","), but what if you don't know the decimal separator at design time? A quick and easy way to figure out what the current locale's decimal separator is: divide 1 by 2 (we know that if we convert this division result to string, a decimal separator would be the second character). Here's a handy function that can be used in scripts:

   1:  Public Function GetDouble(strNumeric)
   2:      strDecSep = Mid(CStr(1/2),2,1)
   3:      strNumeric = Replace(strNumeric, strDecSep, ".")
   4:      If IsNumeric(strNumeric) Then 
   5:          GetDouble = CDbl(strNumeric)
   6:      Else
   7:          GetDouble = 0.00
   8:      End If
   9:  End Function

1 comment:

HGH Human Growth Hormone said...

I simply would like to give you a huge thumbs up for your excellent info you've got right here on this post. I am coming back to your blog for more soon.