VB6 - convert string to double using specific culture?

I have been a long time C # developer and recently I had to look at some VB6 code. After some digging, we figured out that somewhere we kind of store a number as a string. We are now reading it and our code is very bad at handling cultural differences. Here's an example:

Dim text as String
Dim myVal as Double
Set text = "1,123456"
'This sets the value of myVal to 1123456 on our system - incorrect
myVal = text

Set text = "1.123456"
'This sets the value of myVal to 1.123456 on our system - correct
myVal = text

      

Keeping in mind that this is VB6 and NOT VB.NET, are there any built-in methods, functions, whatever, that can convert a string to a double using a certain culture? Or at least hinting at the conversion that we can deal with a different format?

We are still digging into how the value is written and seeing if we can rearrange the process to give us a consistent result. However, our clients already have (have) data in one format or the other (or both, we check ...), so the correct conversion algorithm or implementation would be the best answer at the moment.

+3


source to share


2 answers


I've used this quick and dirty function in the past to get double text. Here in Argentina, people sometimes use a period and sometimes a comma to separate decimal values, so this function is ready to accept both formats. If only one punctuation was present, he assumed it was a decimal separator.



function ConvertDBL( texto )
    dim retval, SepDecimal, SepMiles
    If texto = "" then texto = "0"
    retval = replace(trim(texto), " ", "")
    If cdbl("3,24") = 324 then
        SepDecimal = "."
        SepMiles = ","
    else
        SepDecimal = ","
        SepMiles = "."
    end if  
    If InStr( Retval, SepDecimal ) > 0 then
        If InStr( Retval, SepMiles ) > 0 then
            If InStr( Retval, SepDecimal ) > InStr( Retval, SepMiles ) then
                Retval = replace( Retval, SepMiles, "" )
            else
                Retval = replace( Retval, SepDecimal, "" )
                Retval = replace( Retval, SepMiles, SepDecimal )
            end if
        end if      
    else
        Retval = replace( Retval, SepMiles, SepDecimal )
    end if
    ConvertDbl = cdbl( retval ) 
end function

      

+7


source


You cannot select an arbitrary culture by passing in a culture object like you can in .Net. You can choose:

  • Features that always use the current locale. CStr

    , Format

    , CDbl

    Etc. Implicit conversions (like in your question) also use the current locale.
  • Features that always use US regional settings (similar to .Net culture invariant). Str

    ,Val



Usually the current regional settings are taken from the control panel. There are rumors you might raise SetThreadLocale

to change locales from code at runtime - never tried it myself.

+2


source







All Articles