David Jones

Alternatives to parseInt()

The Javascript function parseInt() is well used. You have probably used it yourself on several occasions, I know I have.

There is a draw back though.

This is that the parseInt() function guesses the base of your number. Lets look at some examples to show how this could affect you.

parseInt( '06' ); //Returns 6
parseInt( '08' ); //Returns 0

The reason why 08 is returned as zero is that because it begins with a zero javascript assumes it is octal number that you want to parse. You can get around this by declaring the base as the second argument to the function.

parseInt( '08', 10 ); //Returns 8

There are other, shorter ways to convert a string into a integer. See the examples below.

~~'5'; //Returns 5
~~'Foo Bar'; //A non integer returns 0 not NaN
+'45'; //Returns 45
'1.58' * 1; //Returns 1.58

Hope this helps your integer parsing!