Why Does Parseint("09") Return 0 But Parseint("07") Return 7?
Possible Duplicate: Workarounds for JavaScript parseInt octal bug Why does parseInt('09') return 0 but parseInt('07') return 7?
Solution 1:
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.
Solution 2:
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.
Post a Comment for "Why Does Parseint("09") Return 0 But Parseint("07") Return 7?"