Friday, October 19, 2007

parseInt - Javascript issue

What would be the result of the following javascript

var value = "08";
value = parseInt(value);
alert(value);

When we just go through the above script, we would expect the result as "8" should be alerted. But to all our surprise the result would be "0".

Let us analyze how this happened.

when ever the browser tries parseInt("08"), zero in front tells the browser that this is an octal (base 8) number and hence will be returned as "0".

This is the default behavior of the parseInt function, to read more about the function
click here.

So what we need to do in this case?

If we just check the intellisence result for the parseInt, it will be like


So it accepts another one argument called radix, and the definition of radix is as follows

"The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number."

And if the radix parameter is not supplied, browser assumes the following:
  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

So in our case, browser assumed the radix as 8 and returned a value of "0". To solve this issue whenever we are calling the parseInt we should explicitly specify the radix value.

2 comments:

Murali Natarajan said...

How to autoscroll images. The url of images collected to the database to array of string using C#. But i cannot pass it to the Javascript,which is separate script file

Murali Natarajan said...

The array of string collected successfully on the page_load. But i cannot pass the array of string(image url) to the javascript to scroll images automatically). The collecting images passed on the user of the System. i am using the following code to register the array..