Last Updated: November 18, 2020
·
8.589K
· pmaoui

Convert a String to an Int without parseInt()

Using parseInt() is a bad idea mainly because it never fails. Also because some results can be unexpected :

parseInt('09', 10);
// return 0 on firefox, nodejs

 What I use instead :

function cleanInt(x) {
    x = Number(x);
    return x >= 0 ? Math.floor(x) : Math.ceil(x);
}

Why should I do this way ?

if the text is not a number (like "123abc") it returns NaN. It seems for me a better behavior. Also, the function can deal with Infinity which is also a number.

parseInt('123abc',10); //return 123

cleanInt('123abc'); //return NaN

parseInt('Infinity',10); //return NaN

cleanInt('Infinity') //return Infinity

typeof cleanInt('Infinity') // return "number"

4 Responses
Add your response

parseInt works correctly, please look at the docs.

String representations starting with "0" are considered octal numbers. So parseInt('09') starts parsing '09' as octal and stops when if encounters an invalid character ('9' in this case) so you get 0 as result.

Always use the second parameter (radix) with parseInt:

parseInt('09', 10); // returns 9

Browsers like Chrome seem to always assume 10 as default value of the second parameter but you must not rely on that.

Btw, another simple way of converting String to Number is the following:

'09'*1; // 9

It will even work with floats:

'3.14'*1; // 3.14

If you only want integer part, you can use a bitwise operator:

'3.14'|0;  // 3

No quirks that I know of...

over 1 year ago ·

Hi dpashkevich,

Let say you have to get an integer from an input, I would rather this behavior :
cleantInt("123abc") => NaN

than this one:
parseInt("123abc") => 123

Actually because 123abc is REALLY not a number. It actually depends on what you want to achieve but in some cases it can be useful to parse real integers... here is the function that you can use for that.

I knew about |0 but I don't like it because :
it don't return NaN for any string that is not a number.
it is very difficult to read in a project but it's just my opinion :)

over 1 year ago ·
over 1 year ago ·

Maybe this tip is just outdated but parseInt('09', 10) returns 9 in both Node and Firefox

over 1 year ago ·