Normally the function parseInt()
in JavaScript is quite straightforward. Given a string value it returns
an integer. But if the string has leading zeros things are getting a little
bit more interesting.
Recently we used parseInt()
in a web application to calculate the month name from the month number.
The month number was stored as a string with leading zeros due to sorting
reasons.
parseInt("07") returned
as expected 7.
But parseInt("08")
returned NaN,
which means that the string could not be converted to a number. (NaN =
not a number).
With the help form Google and a JavaScript
reference we found the solution.
parseInt()
not only works with decimal numbers but also with others bases. This could
be quite handy if you want to transform a hexadecimal number to a decimal
number. Most of the developers, including me, don't know that there is
a second optional parameter radix for parseInt().
The radix parameter must be a number from 2 to 36 and represents the numeral
system to be used. If you omit this parameter parseInt()
tries to guess the right base from the string.
If the string starts with "0x"
it must be a hexadecimal value. If the string starts with "0"
without the "x" it must be a octal value. For octal values only
numbers from 0 to 7 are allowed. That's the reason why parseInt("07")
works and parseInt("08")
returns an error.
Is parseInt()
used with the right parameter it works as expected.
parseInt("08", 10)
returns 8.