Here’s a strange one for you… We all know that parseInt() is a really useful function for converting a string into an integer. It enables us to take a string, convert it to a number, perform mathematic equations and get the result we are looking for.
However today I was converting some strings into numbers and came across some very strange results from parseInt() when passing strings of numbers with leading 0’s… In fact it stumped me so much that after scratching my head for a few minutes and debugging to make sure I was passing the number correctly, I had to resort to a Google search!
So now I know how dumb I am, I thought I would share the weirdness of parseInt() so that anyone else stumped by this unexpected behaviour can also learn from it, and learn that parseInt() isn't just a simple String to Integer convertor.
So, lets start with the problem and the strange results – below is a few test cases of strings with numbers from 1 – 9, all with leading 0’s:
alert(parseInt('01')); //returns 1 alert(parseInt('02')); //returns 2 alert(parseInt('03')); //returns 3 alert(parseInt('04')); //returns 4 alert(parseInt('05')); //returns 5 alert(parseInt('06')); //returns 6 alert(parseInt('07')); //returns 7 alert(parseInt('08')); //returns 0 alert(parseInt('09')); //returns 0
As you can see, everything works as expected until you reach ‘08’ and ‘09’.
So is this a bug? No
So the moral of this story is to always specify the Radix so that this problem NEVER occurs, no matter what!
alert(parseInt('09', 10)); //returns 0