The Number parseFloat() method

By

Learn how the JavaScript Number.parseFloat() method parses a string into a floating point number, including how it extracts a leading number from text.

~~~

Number.parseFloat() parses a string and returns it as a floating point number:

Number.parseFloat('10') //10
Number.parseFloat('10.00') //10
Number.parseFloat('237,21') //237
Number.parseFloat('237.21') //237.21
Number.parseFloat('12 34 56') //12
Number.parseFloat(' 36 ') //36
Number.parseFloat('36 is my age') //36

Number.parseFloat('-10') //-10
Number.parseFloat('-10.2') //-10.2

It’s the same function as the global parseFloat(). ES2015 added it to the Number object to keep number-related functions in one place, but they behave identically.

How does the parsing work?

The method skips any leading whitespace, then reads characters as long as they form a valid number. Everything after that point is ignored.

That’s why '36 is my age' returns 36: the string starts with a number, and parsing stops at the first space.

As you can see Number.parseFloat() is pretty flexible. But the string must start with a number (after optional whitespace, a sign, or a dot). If it doesn’t, you get NaN:

Number.parseFloat('I am Flavio and I am 36') //NaN

A few more cases worth knowing:

Number.parseFloat('.5') //0.5
Number.parseFloat('1e3') //1000
Number.parseFloat('Infinity') //Infinity

Exponent notation and Infinity are both recognized as valid numbers.

It only handles radix 10

Unlike parseInt(), there is no radix argument. Hexadecimal strings don’t work:

Number.parseFloat('0x10') //0

Parsing stops at the x, so you get 0 instead of 16.

A common pitfall: comma decimals

Look back at '237,21' returning 237. In many countries the comma is the decimal separator, so user input often arrives in that format. parseFloat() treats the comma as an invalid character and stops there, silently dropping the decimal part.

The fix is to normalize the string before parsing:

Number.parseFloat('237,21'.replace(',', '.')) //237.21

When to use Number() instead

If you want strict parsing, where the whole string must be a valid number, use Number() instead:

Number('36 is my age') //NaN
Number('36') //36

My advice: reach for parseFloat() when you want to extract a number from messy text, and Number() when you want to validate that a string is a number.

~~~

Related posts about js: