javascript parseInt is broken

by @jehiah on 2007-09-04 17:33UTC
Filed under: All , Javascript , IE , Firefox , Web

I was debugging some strange errors in a date conversion function I was writing, and I stumbled upon something that amazed me… a strange bug in parseInt


Clearly for the strings '08' and '09' parseInt fails to return the right value. One workaround is easy, use parseFloat.

Why does this happen and where should I report this? I find it extremely odd that it happens in both Firefox and Internet Explorer 6 & 7; there must be some explanation right?

You can test it out for yourself using the FireBug javascript console), or by using one of these two links

alert(parseInt(‘07’)+’ == 7 ?‘)
alert(parseInt(‘08’)+’ == 8 ?‘)

Ok, Ok, so now that I explained how you would expect it to work (and clearly how I expected it to work) I’m going to answer my own question (yes I hate it when I do that too)

The problem is with how parseInt guesses the base of your number. Read the parseInt spec. Instead of always defaulting to base 10, it tries to guess, and if the first character is ‘0’ it thinks you want to parse as an octal number, and if it starts with ‘0x’ it thinks you want hexadecimal.

So, the solution is either to use parseFloat or to always specify your base.

Defaults that change on their own can’t be trusted.

Subscribe via RSS ı Email
© 2023 - Jehiah Czebotar