Skip to content
Advertisement

+ operator vs parseFloat

Example 1 of the knockout extenders page describes a way of rounding user input and making sure it is only numeric.

It works great, but looking through the source they do a peculiar thing that i don’t understand, that is on line 8 they do this:

parseFloat(+newValue)

newValue is a string.

When i initially asked this question I didn’t know what + did – some further poking and a link to a different MDN page from one of the initial answers I got indicate it is a unary operator equivalent to number(str) and that there are some differences between +str and parseFloat(str) (treatment of strings ending in alpha characters and interpretation of hex seem to be the headlines).

I still don’t understand why the + in this case needed to be wrapped in the parseFloat although I am starting to think it might be a typo…

Advertisement

Answer

Citing MDN docs for parseFloat:

parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.

Using [unary plus operator][2] you may be sure that `parseFloat` operates on `Number`, which is only useful if you want to be more strict about results but still want to use a `parseFloat`
parseFloat('0.32abcd') // -> 0.32
parseFloat(+'0.32abcd') // -> NaN
**Update:**

After a bit of digging in docs and running some tests, seems there is no reason to use parseFloat other than parsing strings that may contain numbers with non numeric trails to number, eq:

parseFloat('31.5 miles') // -> 31.5
parseFloat('12.75em') // -> 12.75

For any other cases where your string contains number + is a fastest and prefered way (citing MDN docs for unary plus operator):

unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number.

See parseFloat versus unary test case for how faster it is.

Previous link broken so here is the new test that shows how unary is faster.

Advertisement