Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alert(parseInt("09")); shows me "0" Why? [duplicate]

Tags:

javascript

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

like image 352
Chris Avatar asked Aug 01 '11 15:08

Chris


2 Answers

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);

like image 119
Cipi Avatar answered Sep 21 '22 13:09

Cipi


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."

like image 33
user278064 Avatar answered Sep 19 '22 13:09

user278064