Val

From Xojo Documentation

fa-info-circle-32.png
Val (the global function) is here for compatibility with Visual Basic. You should instead use String.Val.



Method

Val(s as String) As Double

Supported for all project types and targets.

Returns the numeric form of a string, always using US/English notation. For any user-visible numbers, you should use CDbl instead.

Syntax

result = Val(string)
Or
result = stringVariable.Val

Part Type Description
result Double 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 String Any valid string expression.
stringVariable String 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 CDbl function instead. Generally, you will use Val for converting internal data and use CDbl 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:

Dim d As Double
d = Val("10,000.95") // The "," causes the string to stop being converted

returns 10. Use CDbl for data that is from the user as it may contain such characters. CDbl handles imbedded separators in the input string.

Val returns zero if 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 CLong 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

Examples

These examples use the Val function to return the numbers contained in a string.

Dim 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

Dim s As String
s = "12345"
n = s.Val // returns 12345

See Also

CDbl, CLong, CStr, IsNumeric, Str, Format functions; &b, &h, &o literals.