I would have thought it had something to do with octal parsing as it only happens on 8 or 9. It was also thought to be a Chrome bug, but it also replicates in Firefox.
Is this intentional behavior? If so, why?
source to share
The solution here is simple. NEVER call
without specifying the desired value. When you don't pass this second parameter, it
tries to guess that the radix is based on the number format. When he guesses, he is often wrong.
Give a radius like this and you get the desired result:
parseInt("08", 10) == 8;
- If the input string begins with "0x" or "0X", the radius is 16 (Hexadecimal).
- If the input string starts with "0", then the radius is eight (Octal). This feature is non-standard and some implementations intentionally do not support it (they use radix 10 instead). For this, a Reason is always specified when using parseInt.
- If the input string starts with any other value, the radius is 10 (decimal). If the first character cannot be converted to a number, parseInt returns NaN.
So, according to these rules, it
will consider that it
is octal, but then it encounters a digit that is not allowed in octal, so it returns
When you pass a number before
, it has nothing to do, because the value is already a number, so it doesn't try to change it.
source to share
"Is this intentional behavior?"
"If so, why?"
is the notation used to represent the octal number defined in the specification. The symbols
do not exist in octal numbering, so it
uses the first valid number it finds, which is
If you do ...
... the result will be ...
... because a valid number was found at the beginning of the line. Anything that is invalid outside of this is discarded.