Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert vb6 "Val()" to c#?

Tags:

c#

vb.net

I am currently converting vb and vb.net to c# but have an issue. I would strongly like not to use the visualbasic dlls in the converted code and have been doing this fine so far.

But this code

Dim x as Double    'this was error saying it was integer
x = Val("1 23 45 x 6")  ''#x is  12345
x = Val("1..23")    ''#x is 1.23
x = Val("1 1,,,,,2,2..3") ''#x is 1122.3

Does not work the same as vb6 even with using "Val" from the visualbasic.conversion.dll Is there anyone that has solved this to work the same? A c# solution would be best.

like image 723
Aditya Om Avatar asked Oct 27 '25 13:10

Aditya Om


2 Answers

None of the above seemed to satisfy my needs, so I wrote the following:

public static Double Val(string value)
{
    String result = String.Empty;
    foreach (char c in value)
    {
        if (Char.IsNumber(c) || (c.Equals('.') && result.Count(x => x.Equals('.')) == 0))
            result += c;
        else if (!c.Equals(' '))
            return String.IsNullOrEmpty(result) ? 0 : Convert.ToDouble(result);
    }
    return String.IsNullOrEmpty(result) ? 0 : Convert.ToDouble(result);
}

Results of the test data:

"0 1 5.2123 123.123. 1 a" returns 15.21233123

" 1 5.2123 123a" returns 15.21233123

"a1 5.2123 123.123. 1 a" returns 0

"" returns 0

like image 177
ericosg Avatar answered Oct 30 '25 06:10

ericosg


I know nothing of this VisualBasic.Conversion.dll (and neither does google), but the Microsoft.VisualBasic namespace (in Microsoft.VisualBasic.dll) is part of the core framework and perfectly fine and acceptable to use from C#. There are other nice gems in there as well (ie TextFieldParser), but this should have the exact Val() implementation you need.

If this is the library you've already tried and it doesn't seem right, then I'd go take another look at the unit tests on it.

Outside of this, the accepted ways in C# for converting strings to integers are int.Parse(), int.TryParse(), and Convert.ToInt32(). But, like it or not, the Val() function from the Microsoft.VisualBasic.dll library is the closest match you're going to find for your code's existing behavior.

like image 31
Joel Coehoorn Avatar answered Oct 30 '25 06:10

Joel Coehoorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!