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)
SYMPTOMSWhen 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. CAUSEThe 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.WORKAROUNDTo 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 = "22%"
'Remove the % character from the string.
s = s.Replace("%", "")
'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.REFERENCESFor more information, visit the following MSDN Web site:
Modification Type: | Minor | Last Reviewed: | 10/3/2006 |
---|
Keywords: | kbvs2005swept kbvs2005applies kbString kbconvert kbformat kbprb KB819347 kbAudDeveloper |
---|
|