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:

Number.parseFloat(string)
  • 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:

  1. Leading Whitespace: The function ignores leading whitespace in the string before attempting to parse the number.

  2. Decimal Point Handling: The function correctly identifies decimal points and can handle numbers in decimal format.

  3. 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.

  4. NaN for Invalid Input: If the string cannot be converted into a number, it returns NaN.

Example 1: Basic Usage

console.log(Number.parseFloat("3.14")); // 3.14 console.log(Number.parseFloat(" 2.71")); // 2.71 (leading whitespace ignored)

In these examples, the strings are successfully parsed into floating-point numbers.

Example 2: Handling Invalid Characters

console.log(Number.parseFloat("42px")); // 42 console.log(Number.parseFloat("3.14abc")); // 3.14

Here, parsing stops at the first invalid character, resulting in valid floating-point numbers being returned.

Example 3: Invalid Input

console.log(Number.parseFloat("abc")); // NaN console.log(Number.parseFloat(" ")); // NaN (only whitespace)

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.
console.log(Number.parseFloat("1e3")); // 1000 (1 × 10^3) console.log(Number.parseFloat("2.5e-2")); // 0.025 (2.5 × 10^-2)

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.