Wednesday, 20 May 2009

Missing radix parameter

This message is given by JSLint when you are using parseInt() without the second parameter radix. This might cause a problem when the variable passed to parseInt() starts with a 0, which makes JavaScript interpret the value as an octal number. Or if the string even starts with “0x” parseInt() might come up with the idea to see a hexadecimal number.

>>> parseInt("8")
8
>>> parseInt("08")
0
>>> parseInt("010") // A juicy mistake, octal numbers.
8
>>> parseInt("0x10") // Probably rare, but possible, hexadecimals.
16
>>> parseInt("08", 10) // Prevent problems, use the radix.
8
>>> parseInt("010", 10)
10


And if the paramter passed to 
parseInt() is a variable that comes from some other place you can not be sure that the string does not start with a “0″. So using the radix might save a lot of headache.

10 comments:

  1. Just yesterday I was having a similar discussion with a colleague about the radix parameter for parseInt.

    Because one can never be too sure about the tyu of string being parsed and one doesn't want to make assumptions about human input, I decided to use the Number() function that isn't as complex and robust as parseInt.

    :)

    ReplyDelete
  2. Just what I was looking for! Thanks!

    ReplyDelete
  3. material is really good i was stuck for date in client side validation.

    ReplyDelete
  4. Thank you so much. My script worked fine in every browser, except IE7 and below, and it was because of this! Cheers.

    ReplyDelete
  5. Thanks for explanation!

    ReplyDelete
  6. Or you can use a bitewise operator which is at least 5 times faster than parseInt() or Number().
    ex: var number = string >>> 0;

    ReplyDelete
  7. yeah, but why you dont explain it a bit. Why 10, what is this radix thing? should we use always just the value 10 or what if I put in 5 or 66?

    ReplyDelete
  8. Luke, look at the documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt

    It's 10 when you are parsing decimal numbers, which is true for nearly everything.

    ReplyDelete
  9. Great article, it really helped explained a jslint error that I was having.

    The funny part is that I've been using JavaScript for years and never included the radix param.

    ReplyDelete