-1

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug

Why does

parseInt("09") 

return 0 but

parseInt("07") 

return 7?

Community
  • 1
  • 1
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 4
    Not a big fan of lmgtfy answers, but have you tried googling this exact phrase: "Why does parseInt(09) return 0"? – georg Jan 06 '12 at 19:32
  • So many of the question already answered about parseInt() and using the proper radix. – John Hartsock Jan 06 '12 at 19:33
  • It's a javascript gotcha. Check [this](http://stackoverflow.com/questions/850341/workarounds-for-javascript-parseint-octal-bug) StackOverflow answer for more information – Kyle Jan 06 '12 at 19:34

2 Answers2

20

The base for strings starting with 0 can be octal (when a radix is not specified - and depending on the browser).

You are looking for:

parseInt("09", 10)

See the documentation for parseInt:

If radix is undefined or 0, JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal).
  • If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).

The comments for the radix optional parameter (the second one in my example) says this:

While this parameter is optional, always specify it to eliminate reader confusion and to guarantee predictable behavior.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 2
    Not true. The default base for `parseInt` is "intelligent guess" as outlined on MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt. Even that behavior is subject to different browser quirks. – Andrew Whitaker Jan 06 '12 at 19:33
  • 1
    @AndrewWhitaker - Yes, answer already corrected and the information from MDN added. – Oded Jan 06 '12 at 19:35
1

A leading 0 indicated an coal value "020" is 16, "07" is 7, there is no digit "9" in the octal system, hence no conversion!

Use parseInt("09", 10) to get the value 9.

Mithrandir
  • 24,869
  • 6
  • 50
  • 66