vijayjoshi.org - php | javascript | ajax | and all things web

FAQ : Problem with javascript function parseInt

JavaScript function parseInt() is used to parse a string and extract the integer from that string.
Therefore if you do parseInt(“200xyz”), it will return 200.
The problem arises when you do the following:

var value = "010";
alert(parseInt(value)); // incorrect: will alert 8

You had expected 10 but what you got is 8.

Weird behavior, you must be thinking.

Actually not.It is a lesser known fact that parseInt actually takes two arguments, second of which is optional.

First argument is the string to parse and second is radix, which can be any one of base 10, base 2, base 8 or others.

If second argument is not given. parseInt does not always assume it to be 10. It parses the string on following assumptions:

  • If the string starts with “0″, it assumes the radix to be 8 (octal numbers).
  • If the string starts with “0x”, it assumes the radix to be 16 (hexadecimal values).
  • In other cases it assumes radix as 10.

In the above case 010 means 8 in the octal number system.
Value in Octal       Value in Decimal
0                           0
1                           1
2                           2
3                           3
4                           4
5                           5
6                           6
7                           7
10                         8
11                         9
12                         10
13                         11
14                         12
15                         13

So, to get integer 10 from string “010″ always specify the base second argument.

var value = "010";
alert(parseInt(value,10)); // correct: will alert 10

So the rule of thumb is :

Always specify the second parameter (radix) to parseInt function in order to get correct value.

Related Posts

Posted in : FAQ, Javascript
Tags: ,

Leave a Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

* Copy this password:

* Type or paste password here:

55,801 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>