String.Val

From Xojo Documentation

Method

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

Syntax

result = sourceVariable.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.
sourceVariable String Any valid string expression.

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 ToDouble function instead. Generally, you will use Val for converting internal data and use 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 result As Double
Var source As String = "10,000.95"
result = source.Val // The "," causes the string to stop being converted

returns 10. Use ToDouble for data that is from the user as it may contain such characters. ToDouble 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 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

Examples

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

Var result As Double
Var source As String = "12345"
result = source.Val // returns 12345

source = "54.25car45"
result = source.Val // returns 54.25

source = "123.25"
result = source.Val // returns 123.25

source = "123 25"
result = source.Val // returns 123

source = "123,456"
result = source.Val // returns 123

source = "auto"
result = source.Val // returns 0

source = "&hFFF"
result = source.Val // returns 4095

source = "&b1111"
result = source.Val // returns 15

See Also

ToDouble, ToInt64, IsNumeric, Str, Format functions; &b, &h, &o literals.