Javascript Number.parseFloat()

Introduction

The Javascript Number.parseFloat() method parses an argument to a floating point number.

If a number cannot be parsed from the argument, it returns NaN.

Number.parseFloat(value)
Parameter Optional Meaning
value RequiredThe value to parse. This must be a string or a number.

This method has the same functionality as the global parseFloat() function:

Number.parseFloat === parseFloat; // true

If the argument is a number, the number is returned.

If the argument is a string, the string is parsed as a number and the result is returned.

If the argument cannot be parsed to a number, this function returns NaN.

Javascript parseFloat() follows the following rules:

  • If parseFloat() encounters a character other than a plus sign (+), minus sign (-), numeral (0), decimal point (.), or exponent (e or E), it returns the value up to that character.
  • A second decimal point stops parsing.
  • Leading and trailing spaces in the argument are ignored.
  • If the argument's first character cannot be converted to a number, parseFloat() returns NaN.
  • parseFloat() can parse and return Infinity.
  • parseFloat() converts BigInt syntax to Numbers, losing precision. The trailing n character is discarded.

parseFloat() can parse non-string objects if they have a toString or valueOf method.

parseFloat() returning a number. The following examples all return 3.14:

console.log(Number.parseFloat(3.14));
console.log(Number.parseFloat('3.14'));
console.log(Number.parseFloat('  3.14  '));
console.log(Number.parseFloat('314e-2'));
console.log(Number.parseFloat('0.0314E+2'));
console.log(Number.parseFloat('3.14TEST'));
console.log(Number.parseFloat({ toString: function() { return "3.14" } }));

parseFloat() returning NaN. The following example returns NaN:

console.log(Number.parseFloat('FF2'));
console.log(Number.parseFloat('ASDF'));

parseFloat() and BigInt

console.log(Number.parseFloat(9007n));
console.log(Number.parseFloat('9007n'));



PreviousNext

Related