Val (VB6) function equivalent in VB.net

Hi ,

I need to create a function in VB.net that emulate 100% the  old VB6 "Val" function.

I have a project in VB.net that use more then 100/200 calls to this function.

I need to remove all the old vb6 functions calls.

I have created this function:

//
    Public Function S_Val(ByVal Number As Object) As Double

        If Number = Nothing Then Return 0

        If Double.TryParse(Number, 0) = False Then Return 0

        Return Double.Parse(Number)

    End Function
//

but not work in many situations like:


      MsgBox(Val("   222#222,222"))                     ------> 222

        MsgBox(S_Val("  222#222,222"))                 ------> 0

-------------------------------------------------------------

      MsgBox(Val("   222.222,222"))                       -------> 222,222

        MsgBox(S_Val("  222.222,222"))                   -------> 222222,222

-------------------------------------------------------------------

Someone can help me please to create an exact duplicate of val function ?
luca345Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Val exists in VB.NET. Are you saying you are not permitted to use it?
0
luca345Author Commented:
Yes, I need only pure vb.net instructions.
0
käµfm³d 👽Commented:
Would regular expressions be out of the question?
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

luca345Author Commented:
If this solution can solve the problem, for me is good.
0
käµfm³d 👽Commented:
OK. Based on what I see as the definition of Val, I believe this matches functionally:

Public Shared Class HelperMethods
  Private Shared _reg As New System.Text.RegularExpressions.Regex("^\s*(\d+(?:\.\d+)?)", Text.RegularExpressions.RegexOptions.Compiled)

  Public Shared Function S_Val(ByRef Number As Object) As Double
    If Number Is Nothing Then
      Return 0
    ElseIf Number Is GetType(Double) OrElse _
       Number Is GetType(Integer) OrElse _
       Number Is GetType(Short) OrElse _
       Number Is GetType(Long) OrElse _
       Number Is GetType(Single) Then

      Return Number
    Else
      Dim result As Double = 0
      Dim convert As String = Number.ToString()
      Dim m As System.Text.RegularExpressions.Match = _reg.Match(convert)

      If m.Success Then
        result = Double.Parse(m.Groups(1).Value)
      End If

      Return result
    End If
  End Function
End Class

Open in new window


Usage
Dim result As Double = HelperMethods.S_Val("32")

Open in new window

0
käµfm³d 👽Commented:
P.S.

I don't have all the "U" types listed above (e.g. UInteger, UShort, etc.), but it should be easy enough for you to add. I can also explain all of the logic for you if it's not apparent.
0
luca345Author Commented:
Thank you for your code.

Do you think is possible do a function/s and not a class ?

Best Regadrs
0
käµfm³d 👽Commented:
I only put it into a class so I could have the Shared Regex object. A Module gets compiled into a class anyway, so they really are equivalent, but you could break the function out, like so:

Public Shared Function S_Val(ByRef Number As Object) As Double
    If Number Is Nothing Then
      Return 0
    ElseIf Number Is GetType(Double) OrElse _
       Number Is GetType(Integer) OrElse _
       Number Is GetType(Short) OrElse _
       Number Is GetType(Long) OrElse _
       Number Is GetType(Single) Then

      Return Number
    Else
      Dim result As Double = 0
      Dim convert As String = Number.ToString()
      Dim m As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(convert)

      If m.Success Then
        result = Double.Parse(m.Groups(1).Value)
      End If

      Return result
    End If
  End Function

Open in new window

0
luca345Author Commented:
Hi  kaufmed ,

Seem there is some errors.

Please see image attached.
error.png
0
Jacques Bourgeois (James Burger)PresidentCommented:
Could you explain to me why somebody would like to get 222 out of "122#222,222"?

Personnally, if somebody provides me with 222#222,222 as a number, I would reject it as an error.

What is S_Val? This is not a VB6 function.
0
luca345Author Commented:
Hi James,

This is only a test to see if the functions (Val and S_Val) return the some result.

In my county for example 1 million and 10 cent is:

1.000.000,10 (1 million and 10 cent)

if the S_Val return a different result there is the possibility to exchange the cents and the Euros .....

But this in only an example.

Marco

Simply I need a function that return the some result of Val.
0
käµfm³d 👽Commented:
Remove the Shared keyword from the function signature. I think that will remove the other error as well.
0
luca345Author Commented:
I have already do this , but don't remove the second error.

P.S.

Do you known a way to prevent the debug to this function or in one particular module ?
0
käµfm³d 👽Commented:
My fault. It helps if you include the pattern in the call to the function! Change line 16 of your screenshot to:

Dim m As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(convert, "^\s*(\d+(?:\.\d+)?)")

Open in new window

0
Jacques Bourgeois (James Burger)PresidentCommented:
Most of the functions dealing with strings in .NET adjust to the configuration panel as far as formatting is concerned.

If information is transmitted as numbers, the formatting is not important. I would send you 1 000 000.10 from my computer, and it would show as 1.000.000,10 on yours. Since numeric values are not saved with formatting (the value is saved as 1000000.10, the dot being the standard decimal separator for .NET numeric values), the system simply adjust to the Control Panel when displaying a numeric value or taking input from the user and saving it as a numeric value.

As long as you are dealing with user input, your aim as a programmer is to follow that same rule: adapt to the Control Panel. This is done automatically for you by most .NET functions. The best replacement for Val would then be TryParse for the type of numeric value you want to work with. Since you seem to be working with money, Microsoft recommends using the Decimal type. So your Val would be replace by the following:
Dim value As Decimal
If Decimal.TryParse("   222#222.222", value) Then
     'Value is good and follows the format defined in the Control Panel
     MessageBox.Show(value.ToString)	'ToString will display the numeric value without the formatting, the way you want it as a programmer
Else
     'Value cannot be resolved for the format used on this computer
     'The String.Format in the following will display a numeric value in the format defined in the Control Panel
     MessageBox.Show("The value you typed is not a valid numeric format. You should type numbers in the following format: " & String.Format("{0:# ### ###.###}", 1234567.098), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
End If

Open in new window

This is the best way to deal with user input in .NET, because it follows Windows standards. This is equivalent to how Excel works for instance.

If the string you need to convert comes from a file however, you need to know beforehand in which format it will come and then follow the format of the file in the TryParse. Here is what you could use to convert a String from a file that I send you from Montreal, where the Control Panel is usually set to French Canadian (fr-CA):

If Decimal.TryParse("   222#222.222", System.Globalization.NumberStyles.Number, New System.Globalization.CultureInfo("fr-CA"), value) Then

Open in new window


A little more involved than Val, but it can adapt to any situation. In this world of internationalization, this is a must.
0
luca345Author Commented:
(James)

I understand, but apart the county val function return a real number and not decimal.


(kaufmed)

The function return a different value:

//
      Const value = "222.222,00"

        MsgBox(Val(value))              --------------> 222,222

        MsgBox(S_Val(value))           --------------> 222222
//
0
Jacques Bourgeois (James Burger)PresidentCommented:
If you want a real number instead of a decimal, change Decimal by Double.

If you ever work with integer, change for Integer or Long.

TryParse works with most basic types, including dates. It's role is to make sure that the application follows the Windows environement in which it is working.

Here in Canada, we have 3 standards. Then english canadians do not have the same format as the french canadians, and english United States is 20 miles from here. Without those functions, programming would be a chore. This was a chore with Val.

I gave you an example with Decimal because you were talking about cents, so I thought that you were working with money. The old VB6 Currency type does not exists in .NET and Microsoft recommends to replace it by Decimal.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
luca345Author Commented:
OK thank you I have replace the old Val function with another function.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming Languages-Other

From novice to tech pro — start learning today.