The parseInt gotcha

Written by on February 12th, 2008 in Ajax News.

Guyon Morée has posted the old chesnut parseInt gotcha, so I thought I should put it up here as a quick tip:

I was working on some stuff in javascript which involved some date/string parsing when one morning it failed. “That’s weird, yesterday it worked fine!”
After some debugging with FireBug I found parseInt() was failing on me.

It was the 8th of February and it was failing on “08″ as an input string. I opened the FireBug console and entered parseInt(”08″), just to be sure I wasn’t’ getting mad and sure enough, the output was 0. Just as a way of rechecking my sanity I entered parseInt(’07′) and this did return the correct answer, 7.

So I googled the parseInt function and discovered some funky default behavior, which was flagged as deprecated.
The parseInt takes a second radix parameter. With this you can tell parseInt the base your input is in.

All fine, but there are also some prefixes defined, so you can input ‘0xff’ for hexadecimal values. Unfortunately they also thought it would be smart to assign 0 to octal values. So 08 is being intepreted as an octal value.

Even though I think the behavior is error prone, it’s even weirder that it returns 0. I believe it should return something like NaN as it is isn’t a valid number in the assumed base.

Mike Owens posted the Prototype based ‘+’ mapping to do the work for you:

JAVASCRIPT:

[’2008′, ‘02′, ‘11′, ‘06′, ‘21′, ‘03′].map(function(v) { return + v });
# [2008, 2, 11, 6, 21, 3]
 

Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/233664749/the-parseint-gotcha

Comments are closed.



Site Navigation