JavaScript parseFloat()

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

Example

const stringDate = "23.9";

// parse the string to float value let floatDate = parseFloat(stringDate);
console.log(floatDate) // Output: 23.9

parseFloat() Syntax

The syntax of the parseFloat() function is:

parseFloat(string)

parseFloat() Parameters

The parseFloat() function takes in:

  • string - The value to parse. If it is not a string, it is converted to one using ToString abstract operation.

Note: Leading whitespace characters are ignored.


parseFloat() Return Value

  • Returns a floating-point number parsed from the given string.
  • Returns NaN when the first non-whitespace character can't be converted to a number.

Example: Using parseFloat()

console.log(parseFloat("  10  ")); // 10
console.log(parseFloat("  3.14seconds")); // 3.14
console.log(parseFloat("314e-2")); // 3.14
// argument can be anything as long as it has toString or valueOf const obj = { toString: () => "127.0.0.1", };
console.log(parseFloat(obj)); // 127
console.log(parseFloat("JavaScript")); // NaN
// BigInt values lose precision console.log(parseFloat("464546416543075614n")); // 464546416543075600

Output

10
3.14
3.14
127
NaN
464546416543075600

Notes:

  • parseFloat() will parse non-string objects if they have a toString or valueOf method.
  • parseFloat() stops converting a string to float when it encounters a non-numeric character.

Recommended Reading: Javascript parseInt()

Did you find this article helpful?