Microsoft KB Archive/819347

= You receive a &quot;System.InvalidCastException&quot; error when you use the FormatNumber function in Visual Basic .NET or in Visual Basic 2005 =

Article ID: 819347

Article Last Modified on 11/26/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-





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 &quot;%&quot; 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:   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 = &quot;22%&quot; 'Remove the % character from the string. s = s.Replace(&quot;%&quot;, &quot;&quot;) 'The expression is converted to a double value. res = CDbl(s / 100) MsgBox(res)  On the Debug menu, click Start. 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.



Steps to Reproduce the Behavior
 Create a new Visual Basic .NET or Visual Basic 2005 Windows Application project.

By default, Form1 is created.</li> From the toolbox, drag a Button control to Form1.</li>  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(&quot;22%&quot;) MsgBox(dbl) </li> On the Debug menu, click Start.</li> Click Button1.

You receive the exception mentioned in the &quot;Symptoms&quot; section of this article.</li></ol>

<div class="references_section">