2008-06-17

JavaScrpt: parseInt - Remember the Radix

When using the JavaScript parseInt global function, it is a good practice to always specify the radix (or number base), which is the optional second argument for that function. The radix that you would probably use most frequently, 10, is actually the default value in most cases, if that second argument is not specified. However, in a few special cases, it does not work that way, as i had found out after spending some debugging time.

i had written a JavaScript function that takes a date string (e.g. "20080617" representing 17th June, 2008) into separate integer variables representing the day, month and year by making use of the String.substr function (to split the single string into "2008", "06" and "17"), and the parseInt function (to parse each string component into an integer value). So, in this example ("20080617"), we would get the value 2008 for the year variable, 6 for the month variable, and 17 for the day variable.

However, things did not run according to plan, when i tried to parse "20080509" (9th May, 2008) using the function that i had just written. The results of passing that string through the function, were the values of 2008, 5, and 0 for the year, month and day variables respectively. So the value assigned to the day variable was obviously wrong.

The reason for such a result would have been clear (or in fact, i would not have made this mistake) if i had read the "specifications" for parseInt more carefully. From the JavaScript Kit's JavaScript reference, the parseInt function

Parses any string and returns the first valid number (integer) it encounters;


AND

Supports an optional second "radix" parameter to specify the base of the number to be parsed. Without this parameter present, parseInt assumes any number that begins with "0x" to be radix 16, "0" to be radix 8, and any other number to be radix 10.


So, in our second (and negative) example above, what happened was:

The string "2008" was parsed using the default base-10, returning the integer value 2008.

The string "05" was parsed using base-8 (because of the "0" prefix), returning the base-10 integer value 5 (because 5 in base-8 is also 5 in base-10).

The string "09" was parsed using base-8 (because of the "0" prefix). When the parser encountered the character "9", it stopped the parsing at that point (because "9" is not a valid character in the base-8 context). Hence, it returned the integer value of the "0" character, which is 0.

0 comments: