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

Tags:

Leave a Reply