10.07.2009

JavaScript: parseInt() with leading zeros

>>Author:  Bernd Hort
>>Ort:     Hamburg
        
URL: http://www.assono.de/blog/d6plinks/JS-parseInt

Category: JavaScript, Web-Entwicklung


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.

Comments

#1 Danke, hab mir sehr geholfen - definitiv besser als die Microsoft Hilfe! Gravatar Image
#2 Danke auch! Habe bei einer PLZ-Funktion ähnliche Probleme gehabt. Gravatar Image
#3 Schade, ich dachte, ich hätte einen Fehler in TraceMonkey gefunden;) Gravatar Image

Post A Comment

Comments

:-D:-o:-p:-x:-(:-):-\:angry::cool::cry::emb::grin::huh::laugh::lips::rolleyes:;-)

Tags

Deutsche RSS-Feeds (German)

Custom Button Custom Button

English RSS feeds

Custom Button Custom Button