Javascript ajax return while using Parseint and radix in calculation

I had some fun the other day, or small challenge, when I needed to take the text being returned by and Ajax call on a php page and use it in a calculation. I was using Javascript.

Besides the usual checking to make sure the data was safe to use I needed to turn the text into an integer and use that in my calculations.

So I pulled out the handy tool parseInt(). ParseInt takes a string and converts it into an integer.

Let’s look at what happens when I use console.log in Chrome on the Mac:
console.log(parseInt(‘7′));
It returns 7 as it should.

What if I add a zero in front of the 7
console.log(parseInt(’07’));
It also returns 7. At this point you are probably saying to yourself, why wouldn’t it return 7?

Let’s go one more step further… how about:
console.log(parseInt(‘070’));
Returns 70.

So now let’s try this on Internet Explorer 8.
console.log(parseInt(‘070’));
The answer is an unbelievable 56! Or is this really so unbelievable. Maybe it’s correct?

Let’s break down the different numbers that computers use:
Octal = 070
Decimal= 0×8²+7×8¹+0×8⁰ = 56
Binary = 111000
Hex = 38

Is that funny, seems like there is an Octal/Decimal thing going on here. We’ll as it turns out parseInt() has a parameter that can be used called the radix. You add the radix right after the string you are trying to convert like this:
parseInt(‘070’, 10)

The radix is the number type that you are parsing from. So in our case I’m telling parseInt that our number is a decimal number (by adding a radix of 10) and so parseInt will parse the string as a decimal number to a decimal integer.

When we try this again in Internet Explorer 8:
console.log(parseInt(‘070’, 10));
We finally get the answer 70 which is what we expect.

And just to be sure let’s try parsing an Octal number to a decimal number:
console.log(parseInt(‘070’, 8));
Answer: 56

So the bottom line is that you really should go back to all your code and add in the radix so that you know exactly what to expect from your parseInt conversions. Most likely you will be parsing decimal to decimal and so you’ll mostly be adding “,10” to your parseInt function. You might think this is overkill but you never know when something so innocent can cause you hours of headaches tracing the bug.

 

Comments: