Click here to Skip to main content
Click here to Skip to main content

parseInt in Javascript

, 23 Mar 2012
Rate this:
Please Sign up or sign in to vote.
parseInt('08') and parseInt('09') returns 0 because it interprets it as octal number

I came across an issue with javascript inbuilt method parseInt().  

While parsing the string ‘08’ or ‘09’ to int using parseInt('08') and parseInt('09'), it is returning as ‘0’. But I was expecting it to return ‘8’ and ‘9’ accordingly. For other strings ‘01’, ‘02’, etc it was working fine and returning ‘1’ and ‘2’ accordingly.In order to fix this issue, add base 10 in parseInt method.   

Cause of the Issue:- parseInt('08') and parseInt('09') returns 0:

The solution:

The parseInt function has an optional 'radix' parameter which specifies the base to use. By passing 10 as the base it solves the leading 0 issue. 
for example: alert(parseInt('08', 10)); will show the number 8 in an alert dialogwhereas: alert(parseInt('08')); would display 0.  

So the best practice is to add base 10 in parseInt method. Refer attached HTML file. 

Hope this help!   

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Peace ON
Software Developer (Senior)
India India
Short Stories Stories We Live...

Comments and Discussions

 
Suggestionpersonal way to convert string to number Pinmemberlittlewater2-Apr-12 15:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 23 Mar 2012
Article Copyright 2012 by Peace ON
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid