30

How to parseInt "09" into 9 ?

ajax333221
  • 11,436
  • 16
  • 61
  • 95
khelll
  • 23,590
  • 15
  • 91
  • 109

6 Answers6

57

include the radix:

parseInt("09", 10);
Gabe Moothart
  • 31,211
  • 14
  • 77
  • 99
12

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.

codeulike
  • 22,514
  • 29
  • 120
  • 167
5

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);
    }
  }
})();
TDot
  • 47
  • 1
  • 1
5

You can also do:

Number('09') => 9

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

2
parseInt("09", 10);

or

parseInt(parseFloat("09"));
Praveen
  • 55,303
  • 33
  • 133
  • 164
JonH
  • 32,732
  • 12
  • 87
  • 145
2
parseInt("09",10);

returns 9 here.

It is odd.

alert(parseInt("09")); // shows 9. (tested with Opera 10)
JCasso
  • 5,423
  • 2
  • 28
  • 42
  • @JonH: Right. Thanks for warning. Since he wrote string instead of String I was mistaken. – JCasso Oct 09 '09 at 17:59
  • 1
    Depending on the browser and version parseInt("09") can return 0. It is a bug. – JonH Oct 09 '09 at 18:34
  • @JonH: can you please check this: http://www.w3schools.com/jsref/jsref_parseInt.asp document.write(parseInt("010") also displays 10 here. – JCasso Oct 09 '09 at 18:39
  • 2
    @JonH: It's not actually a bug. ECMAScript allows implementations to treat numbers with leading zeros as octal. Some implementations do, and some don't. – Matthew Crumley Oct 09 '09 at 19:27
  • 2
    @MatthewCrumley—an old comment but what the heck - [ES5](http://ecma-international.org/ecma-262/5.1/#sec-15.1.2.2) removes that behaviour, so compliant browsers *should* treat `parseInt('08')` as base 10. – RobG Sep 14 '12 at 10:42