Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

parseInt not returning octal number

This lesson: JavaScript Foundations > Numbers > Parsing Numbers From Strings

This code:

var j = parseInt("012"); 

In the video, "j" returns a value of "10" because prepending "12" with a zero indicates that this string should be interpreted as an octal (when it is converted into an integer).

My console (latest versions of Safari & Chrome) is returning "12" (the integer). i.e. it seems to be ignoring the octal and treating the integer as a decimal number.

var x = 012; // this does get interpreted as an octal and returns 10

Interestingly, Firefox does interpret "j" as an octal. Is this simply a browser issue? Any idea what's going on?

Thanks !

2 Answers

James Barnett
James Barnett
39,199 Points

You can save yourself the headache by explicitly specifying the base you want

To make sure a number is interpreted as octal just explicitly specify the base

var j = parseInt ('11', 8); //that's 11 in octal or 9 in decimal

Alternatively if you want to use a leading zero with a decimal number, just specify the base there as well.

var j = parseInt('012',10); //that's 12 in decimal

Thanks James. That life-saving tip is actually in the lesson as well. And as I learn to code and make things for real-life, I will certainly specify the base.

I guess what I was wondering is whether it was just a browser bug or if I was doing something wrong.

My research leads me to believe browser bug / inconsistencies between browsers. But I was hoping someone with more experience than I could weigh in.