[Javascript] – Parsing integers with trailing “0” with parseInt

We are always learning, sometimes not the best way :)

As most of the times, when I develop in JavaScript, I end up using the chrome debugger as it’s lighter than its IE counterpart.

On a project, I had to retrieve some dates from DOM elements and process them, place the elements in the proper position.

The dates were on the following format: “MM:YY”. It means that February is “02” and September is “09”.

While on chrome the parsing of those texts were ok:
parseInt(“02″) -> 2
parseIng(“09″) -> 9
on IE9 and IE11 they were inconsistent:
parseInt(“02″) -> 2
parseInt(“09″) -> 0

Apparently parseInt works in OCTAL mode by default when the string starts with a “0”. Since in octal mode 8 and 9 don’t exist, it returns 0, for IE 8 Document mode.

Like it or not, it is designed like that, when you use IE 8 Document Mode (which you necessarily use for sharepoint 2010).

JsBin (set your browser to IE 8 Document Mode and ignore the JSBIN javascript errors caused it causes):
JsBIN

So, it’s necessary to force the decimal mode:
parseInt(“09″,10) -> 9

So from now on, I’ll always specify the decimal mode, just in case.

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>