18

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug

I've been working on a javascript function, setting date objects by declaring the year, month & date. However, when the month has a value of 08 or 09, 0 is returned when using parseInt(). See below:

parseInt("01") //returns 1
parseInt("02") //returns 2
parseInt("03") //returns 3
parseInt("04") //returns 4
parseInt("05") //returns 5
parseInt("06") //returns 6
parseInt("07") //returns 7
parseInt("08") //returns 0?
parseInt("09") //returns 0?
parseInt("10") //returns 10

I've created a jsFiddle to demonstrate this issue:

http://jsfiddle.net/GhkEf/

Why does parseInt("08") and parseInt("09") return 0?

Community
  • 1
  • 1
Curtis
  • 101,612
  • 66
  • 270
  • 352
  • http://stackoverflow.com/questions/6410009/what-do-you-think-parseint08-will-return?rq=1 – gray state is coming Sep 07 '12 at 13:13
  • 2
    Read the MDN docs: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt This issue is well documented – Šime Vidas Sep 07 '12 at 13:14
  • @ŠimeVidas Ahh of course! Friday afternoon hiccup! Thanks for your responses – Curtis Sep 07 '12 at 13:15
  • 1
    I voted to reopen because Unlike [How do I work around JavaScript's parseInt octal behavior?](https://stackoverflow.com/questions/850341/how-do-i-work-around-javascripts-parseint-octal-behavior) this question is more well suited at people who don't already know that this is due to octal notation – Sam I am says Reinstate Monica Feb 06 '19 at 00:01

4 Answers4

45

That's because numbers started with 0 are considered to be octal. And 08 is a wrong number in octal.

Use parseInt('09', 10); instead.

zerkms
  • 249,484
  • 69
  • 436
  • 539
5

It's being parsed as an octal number. Use the radix parameter in parseInt.

parseInt('08', 10);

An update: As of ES5, browsers should not have this bug. Octal literals require to be in the form 0o12 to be considered Octal numbers. 08 by default is now considered a decimal number in ES5, however, all browsers may not support this yet, so you should continue to pass the radix parameter to parseInt

Some Guy
  • 15,854
  • 10
  • 58
  • 67
1

You can fix this by including the radix, e.g.:

parseInt("08", 10); // outputs 8
Paddy
  • 33,309
  • 15
  • 79
  • 114
1

You need to add a radix of ten:

parseInt("08", 10);

Some implementations default to octal.

Sepster
  • 4,800
  • 20
  • 38