Javascript parseFloat()

Introduction

The Javascript parseFloat() function parses an argument and returns a floating point number.

parseFloat(value)
Parameters Meaning
valueThe value to parse. Must be a string or a number.

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(parseFloat(3.14));//  www.  ja  v  a 2 s .  c o m
console.log(parseFloat('3.14'));
console.log(parseFloat('  3.14  '));
console.log(parseFloat('314e-2'));
console.log(parseFloat('0.0314E+2'));
console.log(parseFloat('3.14TEST'));
console.log(parseFloat({ toString: function() { return "3.14" } }));

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

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

parseFloat() and BigInt

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



PreviousNext

Related