0

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug

Given this script:

<script type="text/javascript">
    var noproblem07 = parseInt("07") - 1;
    alert("No problem (07): " + noproblem07);
    var problem08 = parseInt("08") - 1;
    alert("Problem (08): " + problem08);
    var problem09 = parseInt("09") - 1;
    alert("Problem (09): " + problem09);
    var noproblem10 = parseInt("10") - 1;
    alert("No problem (10): " + noproblem10);
</script>

Why do "08" and "09" resolve to -1?

Community
  • 1
  • 1
Mike Cheel
  • 12,626
  • 10
  • 72
  • 101
  • 1
    refer to the 2nd parameter for [parseInt](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt) – Yoshi Aug 06 '12 at 18:02

2 Answers2

3

Because parseInt parses strings with leading zeros as octal. To get around this, use the radix argument to parseInt:

>>> parseInt("08")
0
>>> parseInt("08", 10)
8
kojiro
  • 74,557
  • 19
  • 143
  • 201
1

Because the browsers you run in it don't implement the specification correctly and try to parse them as octals, resulting in 0

It works fine in IE9 and safari 6. You can pass a second parameter to make it correct in all browsers:

parseInt(x, 10);
Esailija
  • 138,174
  • 23
  • 272
  • 326
  • They are probably implementing the specification just fine. They are just implementing an *older* specification. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt#ECMAScript_5_Removes_Octal_Interpretation – kojiro Aug 06 '12 at 18:04
  • @kojiro You think chrome and firefox are implementing es3? They implement es5, but incorrectly regarding this issue. – Esailija Aug 06 '12 at 18:06
  • This is across the board in chrome, firefox and IE9. – Mike Cheel Aug 06 '12 at 18:08
  • It doesn't matter what I think they're implementing. All that matters is that there is a specification for ECMAScript that allows `parseInt` to have this behavior. – kojiro Aug 06 '12 at 18:09
  • @kojiro That specification is irrelevant because it is not being implemented by the browsers I was referring to but es5 is. – Esailija Aug 06 '12 at 18:17