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.
Just yesterday I was having a similar discussion with a colleague about the radix parameter for parseInt.
ReplyDeleteBecause 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.
:)
Just what I was looking for! Thanks!
ReplyDeletematerial is really good i was stuck for date in client side validation.
ReplyDeleteThank you so much. My script worked fine in every browser, except IE7 and below, and it was because of this! Cheers.
ReplyDeletethanks a lot !!
ReplyDeleteThanks for explanation!
ReplyDeleteOr you can use a bitewise operator which is at least 5 times faster than parseInt() or Number().
ReplyDeleteex: var number = string >>> 0;
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?
ReplyDeleteLuke, look at the documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt
ReplyDeleteIt's 10 when you are parsing decimal numbers, which is true for nearly everything.
Great article, it really helped explained a jslint error that I was having.
ReplyDeleteThe funny part is that I've been using JavaScript for years and never included the radix param.