JavaScript Number.parseFloat(string) function
The Number.parseFloat(string)
function in JavaScript is a static method used to parse a string argument and convert it into a floating-point number. It is part of the Number
object and provides a reliable way to extract numeric values from strings that represent decimal numbers.
Syntax:
string
: The string to be parsed. It can contain numeric characters, decimal points, and whitespace.
Return Value:
- Returns the parsed floating-point number if the string can be converted to a valid number; otherwise, it returns
NaN
(Not-a-Number).
Key Characteristics:
Leading Whitespace: The function ignores leading whitespace in the string before attempting to parse the number.
Decimal Point Handling: The function correctly identifies decimal points and can handle numbers in decimal format.
Stops Parsing at Invalid Characters: Parsing stops when the function encounters a character that is not part of a valid number (e.g., letters, special symbols) after successfully reading the number.
NaN for Invalid Input: If the string cannot be converted into a number, it returns
NaN
.
Example 1: Basic Usage
In these examples, the strings are successfully parsed into floating-point numbers.
Example 2: Handling Invalid Characters
Here, parsing stops at the first invalid character, resulting in valid floating-point numbers being returned.
Example 3: Invalid Input
In these cases, the strings cannot be converted into valid numbers, so the function returns NaN
.
Example 4: Edge Cases
- Scientific Notation: The function can also parse numbers in scientific notation.
Summary:
- The
Number.parseFloat(string)
function is a straightforward way to convert strings representing decimal numbers into floating-point numbers in JavaScript. - It gracefully handles leading whitespace, ignores invalid characters after a valid number, and returns
NaN
for non-numeric inputs. - This method is useful for parsing user inputs or data read from sources where numbers may be formatted as strings.