When parseInt() doesn’t return the expected value

Once, I was working on a JavaScript application that required converting time from the US format (hh:mm:ss [AM|PM]). As I had to perform some conversion on the time members, I encountered a weird bug, where the application would return the wrong value, but not always. As I was investigating that bug, I realized that I was not using parseInt() properly.The parseInt function takes one mandatory argument (the string to parse), plus a less known optional argument, that defines which base is used for the conversion.

parseInt(string[, base]);

There is in an implicit rule that defines which base is used when the optional parameter is not specified:

  • Base 10 is the default
  • Base 8 (octal) is used if the string starts with “0”
  • Base 16 (hexadecimal) is used if the string starts with “0x”

The hours and minutes in my application were formatted as HH:MM. Because of the rule above, if you try parsing “07” without specifying the base, it works fine, and returns 7 as expected. However, if you try the same but with “08” instead, the parseInt function will return 0.

To make sure the conversion works every time I had to append the base parameter.

var n = "08";
var octal = parseInt(n); // Returns 0
var decimal = parseInt(n, 10); // Returns 8

It took me some time to figure out why my code was not working, so I thought it would be a good idea to share that tip on my blog.

Advertisements

2 Responses to “When parseInt() doesn’t return the expected value”

  1. drj11 Says:

    It’s slightly worse than you think. If the string starts with a «0» (but not «0x») then JavaScript can assume it is base 8 or base 10, at the implementation’s discretion (see step 12 of section 15.1.2.2 of ECMA 262). Different implementations (in different browsers) may do different things.

    Moral: always pass a base to parseInt

  2. sandrar Says:

    Hi! I was surfing and found your blog post… nice! I love your blog. 🙂 Cheers! Sandra. R.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s


%d bloggers like this: