parseInt issue

It seems that parseInt has very strange results.

=>parseInt('07')
7.0
=>parseInt('08')
NaN
=>parseInt('09')
NaN
=>parseInt('10')
10.0
=>parseInt('010')
8.0

Can anybody explain why parseInt has these strange results.
If this is the default for parseInt then how can we rely on the results?

Hi Jos,

When you use leading zeros parseInt treats it as an base 8 value (octal).
Use the optional radix parameter like so parseInt(‘09’, 10) to make it use base 10. This will give you the proper values you expect.

Hope this helps.

As a side note you can use this function in tandem with the toString() function to create shortURL functionality like Bitly and other URL shorteners uses:

function integerToShortURL(_nVal) {
	return _nVal.toString(36); // base36
}

And back again:

function shortURLToInteger(_sUrl) {
	return parseInt(_sUrl, 36); // base36
}

JavaScript is a powerful language ;)

Ah, that explains it!

Thank you.