You receive a "System.InvalidCastException" error when you use the FormatNumber function in Visual Basic .NET or in Visual Basic 2005 (819347)



The information in this article applies to:

  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

SYMPTOMS

When you have a string with the percent character (%) as an argument in the FormatNumber function in a Visual Basic .NET or Visual Basic 2005 application, you receive the following exception if you run the application:
An unhandled exception of type 'System.InvalidCastException' occurred in microsoft.visualbasic.dll Additional information: Cast from string "%" to type 'Double' is not valid.

CAUSE

The string argument in the FormatNumber function is converted to a double value by using the Double.parse method. This parse method uses Globalization.NumberStyles to parse the arguments. There is no NumberStyle enum member that allows the percent character. Therefore, when the argument has a string with a percent character, Visual Basic .NET or Visual Basic 2005 does not allow casting the string to a valid double value.

WORKAROUND

To work around this problem, follow these steps:
  1. Replace the existing code in the Button1_Click event handler with the following Visual Basic .NET code:
     Dim s As String
            Dim res As Double
            'Expression to be formatted to a number.
            s = "22%"
            'Remove the % character from the string.
            s = s.Replace("%", "")
            'The expression is converted to a double value.
            res = CDbl(s / 100)
            MsgBox(res)
  2. On the Debug menu, click Start.
  3. Click Button1.

STATUS

This behavior is by design.Note This problem does not occur in Microsoft Visual Basic 6.0. The application with the FormatNumber function runs successfully and displays the correct result.

MORE INFORMATION

Steps to Reproduce the Behavior

  1. Create a new Visual Basic .NET or Visual Basic 2005 Windows Application project.

    By default, Form1 is created.
  2. From the toolbox, drag a Button control to Form1.
  3. Add the following Visual Basic .NET or Visual Basic 2005 code to the Button1_Click event handler:
    Dim dbl As Double
    'Format the expression to a number.
    dbl = FormatNumber("22%")
    MsgBox(dbl)
  4. On the Debug menu, click Start.
  5. Click Button1.

    You receive the exception mentioned in the "Symptoms" section of this article.

REFERENCES

For more information, visit the following MSDN Web site:

Modification Type:MinorLast Reviewed:10/3/2006
Keywords:kbvs2005swept kbvs2005applies kbString kbconvert kbformat kbprb KB819347 kbAudDeveloper