Name

parseFloat( ) Global Function — extract a floating-point number from a string

Availability

Flash 5

Synopsis

parseFloat(stringExpression)

Arguments

stringExpression

The string from which a floating-point number is to be extracted.

Returns

The extracted floating-point number. Or, if extraction was unsuccessful, the special numeric value NaN.

Description

The parseFloat( ) function converts a string to a floating-point number (a number with a fractional portion). It works only with strings that contain a valid string representation of a floating-point number; otherwise, NaN is returned. The string must be of the following form:

  • Optional leading whitespace

  • Optional sign indicator + or -

  • At least one digit from 0-9 and an optional decimal point

  • Optional exponent starting with e or E followed by integer exponent

Trailing characters that cannot be parsed as part of the preceding numeric form are ignored.

Usage

Because user input data entered into text fields always belongs to the string datatype, we often use parseFloat( ) to extract numeric data from user-entered text. Note that parseFloat( ) can extract numbers from strings that contain both numbers and non-numeric characters, whereas Number( ) cannot.

Examples

parseFloat("14.5 apples");    // Yields 14.5
parseFloat(".123");           // Yields 0.123
var x = "15, 4, 23, 9";
parseFloat(x);                // Yields 15

See Also

isNaN( ), NaN, Number( ), parseInt( ); Section 3.4.2 in Chapter 3; Section 4.2 in Chapter 4

Get ActionScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.