Auf dieser Website werden Cookies gesetzt, die für den sicheren Betrieb technisch erforderlich sind. Siehe: Datenschutz

JavaScript: parseInt() with leading zeros

by Bernd,
assono GmbH, Standort Hamburg,

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. smile.gif

Technical article JavaScript Development

You have questions about this article? Contact us:

Sie wollen eine individuelle Beratung oder einen Workshop? Read more

More interesting entries

Any questions? Contact us.

If you want to know more about our offers, you can contact us at any time. There are several ways to contact us for a non-binding first consultation.

We don’t sell your data. 100% guaranteed. See: Privacy Policy
assono GmbH

Location Kiel (headquarters)
assono GmbH
Lise-Meitner-Straße 1–7
24223 Schwentinental

Location Hamburg
assono GmbH
Bornkampsweg 58
22761 Hamburg

Phone numbers:
Human resources department: +49 4307 900 407
Marketing department: +49 4307 900 402

E-Mail adresses: