Tuesday 12 July 2011

parseInt('08') returns 0 with Javascript

I came across a rather interesting problem with the Javascript parseInt() function a couple of days ago; if the value is a zero padded string and is '08' or '09' then parseInt() will return 0.

parseInt('08') returns 0

The leading zero in the string tells the Javascript engine that it is an octal number. Because 8 and 9 are not valid numbers in octal, parseInt returns 0. This is expected behaviour because they are not valid octal integers and parseInt returns 0 because the first valid number encountered is a zero.

The solution

After a quick bit of research when I had this problem, I discovered the parseInt function has an optional 'radix' parameter which specifies the base to use. By passing 10 as the base it solves the leading 0 issue, for example:

alert( parseInt('08', 10) );

will show the number 8 in an alert dialog, whereas:

alert( parseInt('08') );

would display 0.

Conclusion

To be on the safe side it's probably always a good idea to pass the radix parameter to the parseInt function to ensure the values returned are what you expect them to be, especially if they might contain leading zeroes.

No comments:

Post a Comment