Core Function Atof
Atof( <variable>, <count>, <start> )
Contents |
Description
Convert string to Double.
Parses the string, interpreting its content as a floating point number and returns its value as a double.
The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found.
Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals (see below), and interprets them as a numerical value.
The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.
If the first sequence of non-whitespace characters in string does not form a valid floating-point number as just defined, or if no such sequence exists because either string is empty or contains only whitespace characters, no conversion is performed and the function returns 0.0.
Parameters
variable
A string beginning with the representation of a floating-point number.
(It does not need to fully be a floating-point number just begin with one)
count
Optional; If you supply a variable for this parameter it will be given the number of characters that the floating-point number is made up from out of the string.
See example.
start
Optional; Start position to begin searching the haystack from.
Can be negative this will cause it to start from haystack length - abs(start) instead.
Default: 0
Return Value
On success, the function returns the converted floating point number as a double value.
If no valid conversion could be performed, the function returns zero (0.0).
If the converted value would be out of the range of representable values by a double, it will set to the @Double_Max, @Double_Min or 0.0 depending on the issue at hand.
Remarks
This is useful for when you wish to exact a number from a string even if the entire string is not suitable as a number and would normally return 0.
Using this you can extract the number you desire advance along the string using the count and continue.
Example
$var = atof( "77.42Hello" ); say $var; // Prints: 77.42
Example of getting how many characters were extracted from the string
$var = atof( "77.42Hello", $count ); say $var; // Prints: 77.42 say $count; // Prints: 5 // Since there were 5 chars in the floating-point
Example of using start parameter
// Search begins at index 6 of the string so it is able to find a valid floating-point $var = atof( "Hello 777.42 hmmm", null, 6 ); say $var; // Prints: 77.42
Example of using negative start parameter
// Search begins at index -3 (-3 turns out to be haystack length - abs(-3) of the string // so it is able to find a valid floating-point $var = atof( "Hello 777.42 h789", null, -3 ); say $var; // Prints: 789