Last Updated: February 25, 2016
·
2.334K
· aleclanter

JavaScript parseInt and default radix

I learned the hard way that JavaScript's parseInt(string) method assumes any value with a leading '0' is in base8. To complicate matters, there is a bug in the way Chrome's JavaScript engine deals with base 8 numbers. I had the following two use cases:

var month1 = parseInt("04");
var month2 = parseInt("08");

month1 was coming back as expected, (int)4, but month2 was coming back as 0. Changing to an explicit radix of 10 fixes the issue:

var month2 = parseInt("08",10);

So, watch out for leading zeros mucking with your string-to-int conversions. And someone should let the Chrome JS engine's devs know that '08' is not 0 in base 8, it should be NaN. ;)

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside