Updated: July 2008
Returns the numbers contained in a string as a numeric value of appropriate type.
Public Overloads Function Val(ByVal InputStr As String) As Double ' -or- Public Overloads Function Val(ByVal Expression As Object) As Double ' -or- Public Overloads Function Val(ByVal Expression As Char) As Integer
InputStr is too large.
Object type expression not convertible to String.
See the "Error number" column if you are upgrading Visual Basic 6.0 applications that use unstructured error handling. (You can compare the error number against the Number Property (Err Object).) However, when possible, you should consider replacing such error control with Structured Exception Handling Overview for Visual Basic.
An InvalidCastException exception, error number 13, might be raised in response to certain uncommon number formats. For more information about this error, see Type mismatch (Visual Basic). For example, the following code raises the exception.
' These examples cause run-time errors.
The conflict between the number formatted as a Double and the Integer and Long type characters would be caught by the compiler if it were not hidden in a string.
' These examples cause compiler errors.
'Dim m = 1.34%
'Dim n = 1.34&
The Val function stops reading the string at the first character it cannot recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function recognizes the radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the argument.
The following call returns the value 1615198.
Val(" 1615 198th Street N.E.")
The following call returns the decimal value -1.
The Val function recognizes only the period (.) as a valid decimal separator. When different decimal separators are used, as in international applications, use CDbl or CInt instead to convert a string to a number. To convert the string representation of a number in a particular culture to a numeric value, use the numeric type's Parse(String, IFormatProvider) method. For example, use Double.Parse when converting a string to a Double.
The following example uses the Val function to return the numbers contained in each string. Val stops converting at the first character that cannot be interpreted as a numeric digit, numeric modifier, numeric punctuation, or white space.
Assembly: Visual Basic Runtime Library (in Microsoft.VisualBasic.dll)