This question already has an answer here:
-
How to parseInt a string with leading 0
6 answers
i have parseInt function.
for 010 as input :
output in IE : 8
output in chrome and firefox: 10
for 099 as input:
output in IE : 0
output in chrome and firefox: 99
Could someone plz help me understand this different behaviour in the browsers..
issue is in IE and it is working as expected in chrome and firefox.
Thanks in advance.
Actually I would argue IE is doing things correctly* here . parseInt
for a string starting with a 0
is treated as octal input.
To fix the problem, specify the base (in this case, you want decimal - 10
):
num = parseInt(str, 10);
* In this case "correctly" really means "traditionally". The specification has actually changed.
Technically, a string starting with 0
can be treated as either octal OR decimal, depending on the implementor's whim, where decimal is now preferred:
If radix is undefined
or 0 (or absent), JavaScript assumes the following:
- If the input
string
begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.