parseInt() is the most popular function used for parsing strings into numbers. But have you ever thought about the differences comparing parseInt to Number()? Or did you know that you can parse number using just one character, the unary operator “+”?
parseInt()
Function parseInt() will try to return an absolute number using provided string. Non number characters will be skipped and function will try to take the first correct number character. When the first character cannot be converted to number then we will get NaN (Not-a-Number).
parseInt('10rem'); // 10 parseInt('111Hello!!'); // 111 parseInt('111Hello111'); // 111 parseInt('acdc123'); // NaN parseInt(' 123'); // 123 parseInt(' 1 2 3'); // 1 parseInt(false); // NaN
Number()
This object will try to convert to a number entire string. If this is not possible then we will get NaN.
Number('10rem'); // NaN Number('111Hello!!'); // NaN Number('111Hello111'); // NaN Number('acdc123'); // NaN Number(' 1 2 3'); // NaN Number(' 123'); // 123 Number(true); // 1 Number(false); // 0
As you can see the result for passing boolean argument will be different. Unlike parseInt(), Number() will return either 1 or 0 instead of NaN.
Number() has also static method – Number.parseInt() which is the same as the global parseInt() function.
Unary Operator (+)
We do not use here any brackets. Add “+” sign before string and that’s all.
+'10rem'; // NaN +'111Hello!!'; // NaN +'111Hello111'; // NaN +'acdc123'; // NaN +' 1 2 3'; // NaN +' 123'; // 123 +true; // 1 +false;
For given examples this operator will give us the same result as Number().
What should I use?
Comparing the outputs we can tell that for safety reasons Number() is the best choice. Unary operator “+” is also good, but it seems more like a “ninja” code style approach. You need also to remember that Number() and unary operator “+” can’t convert numbers in binary notation. If you need binary notation then global function parseInt() is should be your choice.