parseInt() Function Returning Zero For Numbers ’08’ and ’09’

July 26th, 2012 - Posted by Steve Marks to Javascript / jQuery, Web Development.

A very quick one this but one that had me stumped when trying to work with numbers in JavaScript earlier on.

Lets imagine we have the number eight or nine but it’s prefixed with a zero. To run it through parseInt() in JavaScript you might think to do the following:

var myNumber = parseInt('08');

What you’ll get from the above however is a zero returned. Now, lets take a look at what the JavaScript documentation says about this:

If the string begins with "0", the radix is 8 (octal).

Sound familiar? Good. So to get the function working as expected we need to work in base 10. To do this we simply pass the base as an additional parameter to parseInt() like so:

var myNumber = parseInt('08', 10);

What you’ll now get returned is the expected ‘8’.

This entry was posted on Thursday, July 26th, 2012 at 6:14 pm by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (0)

No comments have been left yet. Be the first