Instant methods: parse_float()
The instant method parse_float() converts the number stored in the string operand in the corresponding float value.
Declaration
float string.parse_float( float aDefault )
Parameters
aDefault
Value to return if the string doesn't contain any valid number.
Discussion
The parse_float() method parses the string operand interpreting its content as a number. The number can be prefixed by an optional + (plus) or - (minus) sign. Eventual whitespace signs ' ' (space), '\t' (tabulator), '\n' (newline), '\v' (vertical tab), '\f' (form-feed) and '\r' (carriage return) lying at the begin of the string are ignored and skipped over.
The number can consist of an integral and/or a fractional portion. The fractional portion starts with a . (period) sign. Optionally the number can be followed by an exponent portion. The exponent portion starts with the e or E sign followed by an optional + (plus) or - (minus) sign and an integral number specifying the exponent. The following example shows a string containing the complete number with all possible portions:
"+123.456e-07"
Generally the method tries to parse as many signs as possible. If the end of the string or an unexpected sign is found, the method stops and returns the already read number as float value. If the string content is invalid (the string doesn't contain any of the expected digits), the value passed in the parameter aDefault is returned instead. For example:
var string s1 = "+13.69"; var string s2 = "-.1369e+04"; var string s3 = " -1251-other content"; var string s4 = "-X2.51"; var float r1 = s1.parse_float( -1.0 ); // r1 = 13.69 var float r2 = s2.parse_float( -1.0 ); // r2 = -1368.999... // Skip over leading whitespace signs and ignore the signs // following the number 1251 var float r3 = s3.parse_float( -1.0 ); // r3 = -1251.0 // The number doesn't start with an expected sign. Thereupon // return the default value. var float r4 = s4.parse_float( -1.0 ); // r4 = -1.0