khelll
khelll

Reputation: 23990

How to parseInt a string with leading 0

How to parseInt "09" into 9 ?

Upvotes: 30

Views: 8923

Answers (6)

JonH
JonH

Reputation: 33143

parseInt("09", 10);

or

parseInt(parseFloat("09"));

Upvotes: 2

TDot
TDot

Reputation: 47

Re-implement the existing parseInt so that if it is called with one argument then "10" is automatically included as the second argument.

(function(){
  var oldParseInt = parseInt;
  parseInt = function(){
    if(arguments.length == 1)
    {
      return oldParseInt(arguments[0], 10);    
    }
    else
    {
      return oldParseInt.apply(this, arguments);
    }
  }
})();

Upvotes: 5

codeulike
codeulike

Reputation: 23064

This has been driving me nuts -parseInt("02") works but not parseInt("09").

As others have said, the solution is to specify base 10:

parseInt("09", 10);

There's a good explanation for this behaviour here

... In Javascript numbers starting with zero are considered octal and there's no 08 or 09 in octal, hence the problem.

Upvotes: 12

Kieran Pilkington
Kieran Pilkington

Reputation: 412

You can also do:

Number('09') => 9

This returns the integer 9 on IE7, IE8, FF3, FF4, and Chrome 10.

Upvotes: 5

JCasso
JCasso

Reputation: 5523

parseInt("09",10);

returns 9 here.

It is odd.

alert(parseInt("09")); // shows 9. (tested with Opera 10)

Upvotes: 2

Gabe Moothart
Gabe Moothart

Reputation: 32082

include the radix:

parseInt("09", 10);

Upvotes: 57

Related Questions