JavaScript parseInt Usage

I have had a bit of a hair pulling experience over the last few hours, until finally I got some sense and looked at the Definition and Usage of parseInt. Here’s the example:

<script type="text/javascript">
   var data = new Array('007', '008', '009', '010');
   for(var x in data)
   {
      console.log(data[x] + ' -> ' + parseInt(data[x]));
   }
</script>

And the result:

007 -> 7
008 -> 0
009 -> 0
010 -> 8

What I wanted was the result 7, 8, 9, and 10. The result seen above comes from the fact that, because I have a leading 0 in my strings, parseInt is reverting to a base 8 (octal) radix. The solution of course is to specify a base 10 (decimal) radix.

<script type="text/javascript">
   var data = new Array('007', '008', '009', '010');
   for(var x in data)
   {
      console.log(data[x] + ' -> ' + parseInt(data[x], 10));
   }
</script>

And the result:

007 -> 7
008 -> 8
009 -> 9
010 -> 10

2 Comments for "JavaScript parseInt Usage"

Comment 1 marco - Gravatar marco

Great! Thanks a lot for this helpfull info!!!! :)

You saved me!

Wed, 21 Jan 2009 05:21:13 +0000 Link

Comment 2 Vikas - Gravatar Vikas

Thanks a lot dear, for the info. I had the same problem but I dint look for the method overload. You indirectly closed my 1 catastrophic bug ..:-)

Mon, 09 Mar 2009 00:54:10 +0000 Link

Comments have been disabled for this post.