Method
Val
Description
Returns the numeric form of a string, always using US/English notation. For any user-visible numbers, you should use String.ToDouble instead.
Usage
result = Val(string)
Or
result = stringVariable.Val
Part |
Type |
Description |
---|---|---|
result |
The numeric equivalent of the string passed, if a numeric equivalent exists. If the passed string does not contain a valid number, then the result is zero. The string is parsed by the operating system, which means that the behavior is platform-specific in the case of an undefined result. |
|
string |
Any valid string expression. |
|
stringVariable |
Any variable of type String. |
Notes
Val recognizes prefixes &o (octal), &b (binary), and &h (hexadecimal). However, spaces are not allowed in front of the ampersand. That is, " &hFF" returns 255, but "&h FF" returns 0.
For localized number formatting, use the String.ToDouble function instead. Generally, you will use Val for converting internal data and use String.ToDouble for converting data for input and output of user data.
It is important to note that Val does not take separator characters into consideration. For example:
Var d As Double
d = Val("10,000.95") ' The "," causes the string to stop being converted
returns 10. Use String.ToDouble for data that is from the user as it may contain such characters. String.ToDouble handles imbedded separators in the input string.
Val returns zero if the string contains no numbers, except in the special case where the string begins with the string "NAN". In this case, it returns "NAN(021)".
As Val converts the string to a double, large integer values in a string could exceed the maximum integer value that a double can hold. In these cases, use String.ToInt64 to convert longer integer strings to Int64 values.
Numbers are converted only if they are found at the beginning of the string. Any numbers that follow a non-numeric value are ignored.
So,
"1AA2" returns 1
"AA2" returns 0
"12AA54" returns 12
Sample code
These examples use the Val function to return the numbers contained in a string.
Var n As Double
n = Val("12345") ' returns 12345
n = Val("54.25car45") ' returns 54.25
n = Val("123.25") ' returns 123.25
n = Val("123 25") ' returns 123
n = Val("123,456") ' returns 123
n = Val("auto") ' returns 0
n = Val("&hFFF") ' returns 4095
n = Val("&b1111") ' returns 15
Var s As String
s = "12345"
n = s.Val ' returns 12345
Compatibility
All project types on all supported operating systems.
See also
String.ToDouble, String.ToInt64, CStr, IsNumeric, Str, Format functions; &b, &h, &o literals.