Getting Weird Results from parseInt?

Originally published on my old QuintusQuill Console blog in January 2009.

If you pass parseInt a number with a zero in front of it, such as "020", without specifying a radix, you may get funny results...

parseInt("020"); // Result: 16

This is because when the input string begins with "0", parseInt assumes the radix is 8 (octal), and converts the string to an octal number. Perhaps it's just me, but I don't usually work in octals!

You can avoid this problem by supplying it with the radix that you want to use.

parseInt("020", 10); // Result: 20

For more information, I recommend that you read the parseInt page at the Mozilla Developer Centre.

Subscribe to my newsletter

Get new articles delivered to your inbox.