14

Possible Duplicate:
Workarounds for JavaScript parseInt octal bug

EXTREMELY confused here.

parseInt("09") = 0

but

parseInt("9") = 9

Why is the prefixed zero not just stripped out?

alert(parseInt("01")); = 1

.. rage quit

Community
  • 1
  • 1
Chris
  • 2,340
  • 6
  • 40
  • 63
  • Not a solution, but rather some background. This is a particularly frustrating problem because the default in Chrome 35+, IE 9-11 and Firefox 4+ seems to be equivalent to __parseInt('09',10)__, but not in IE8 or Safari 5. The safest option is just to use parseInt('08',10), which appears to work cross-browser. – Aaron Newton Jun 05 '14 at 00:00
  • Typo - I meant parseInt('09',10), not parseInt('08',10) – Aaron Newton Jun 05 '14 at 00:47

4 Answers4

20

Because that is treated as octal format, by default. If you want to get 9, you must add number base you want, and thats 10, not 8 (for octal), so call:

parseInt("09", 10);

Cipi
  • 11,055
  • 9
  • 47
  • 60
  • 3
    To clarify, "9" in octal is 0 because the digit 9 does not have meaning in octal (only digits 0 - 7 are allowed), so by default, it is assigned no value. – cheeken Aug 01 '11 at 15:42
  • This is my answer. Will accept in 11 minutes when SO allows. Thankyou to all, and appologies for duplicate, didnt see that one when searching. – Chris Aug 01 '11 at 15:42
  • Because thats how they decided to have string representation of octal nubers. Hexadecimal are prefixed with "0x", and octal are prefixed with "0". Read the answer below... – Cipi Aug 01 '11 at 15:43
6

A.7. parseInt

parseInt is a function that converts a string into an integer. It stops when it sees a nondigit, so parseInt("16") and parseInt("16 tons") produce the same result. It would be nice if the function somehow informed us about the extra text, but it doesn't.

If the first character of the string is 0, then the string is evaluated in base 8 instead of base 10. In base 8, 8 and 9 are not digits, so parseInt("08") and parseInt("09") produce 0 as their result. This error causes problems in programs that parse dates and times. Fortunately, parseInt can take a radix parameter, so that parseInt("08", 10) produces 8. I recommend that you always provide the radix parameter.

"JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc., 978-0-596-51774-8."

user278064
  • 9,982
  • 1
  • 33
  • 46
6

this the reasons:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

http://www.w3schools.com/jsref/jsref_parseInt.asp

Massimiliano Peluso
  • 26,379
  • 6
  • 61
  • 70
5

Do

parseInt("09", 10)

To specify base 10.

Edit: To clarify, a number prefixed by a zero will be assumed to be of octal notation, and "09" isn't a valid octal number.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145