Know JavaScript: parseInt()

The last week I have been writing some JavaScript to improve the user-experience on a web-page I am working on. One of the task I had to do was parsing some String values into integer values for numeric comparison. I googled and found JavaScript’s “parseInt()” function. I added this function, and tested it a few times, happy to see that the function transformed my String values into comparable integer values.

var strValue = "8";
var i = parseInt(strValue) ;
/* i has value 8 */

Later I did some modifications in the service delivering values to my webpage. It was convenient for the layout if all values were two digits, so all values below 10 was zero padded. “1” became “01”, “2” became “02” and so on. After a few days strange bugs were reported. apparently some of the parsed values became 0, an illegal value for my web-application.
After some testing I discovered the following:

  • “01” becomes 1
  • “02” becomes 2
  • “03” becomes 3
  • “04” becomes 4
  • “05” becomes 5
  • “06” becomes 6
  • “07” becomes 7
  • “08” becomes 0
  • “09” becomes 0
  • “10” becomes 10

What is going on? Is there a bug in JavaScript’s parseInt() function? After all I headed to the parseInt() documentation. The documentation clearly states:

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with “0x”, the radix is 16 (hexadecimal)
  • If the string begins with “0”, the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

So this tells us that the parseInt() function also takes a radix parameter.  The above results makes sence because 8 and 9 does not exists in the octal number system.  I changed my code to the following:

var strValue = "08";
var i = parseInt(strValue, 10) ;
/* i has value 8 */

Afte this change I was  happy to see that “08” becomes “8” and “09” becomes “9”. The radix parameter is optional, but I will never leave it out again! Just add the required radix as a second parameter to the function, and you will never will get in trouble parsing String values to integer values!

Advertisements

3 thoughts on “Know JavaScript: parseInt()

  1. Converting it to a Number (alt. prefixing it with a +) also renders your expected value

    Number(strValue) // 8

    +strValue // 8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s