Why does JavaScript convert parseInt(0000000101126) to 33366 instead of 101126?
var example = parseInt(0000000101126);
console.log(example); //33366
Why does JavaScript convert parseInt(0000000101126) to 33366 instead of 101126?
var example = parseInt(0000000101126);
console.log(example); //33366
JavaScript assumes the following:
•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)
Try putting your value in quotes it will give you proper output:
Instead of:
var example = parseInt(0000000101126);
Try
var example = parseInt("0000000101126");
This is because it's being converted to Octal.
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number. If the radix parameter is omitted, JavaScript assumes the following:
- 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)
The trick is that it's not parseInt
which interprets your number as octal, but the JS interpreter.
This section of ECMAScript describes how numbers in source code are interpreted by the JS interpreter. This one describes the grammar for octal numbers.
Some overzelousness of eliminating the ambiguity of octal literals results in interesting scenarios :
(Chrome 32)
01.0 // SyntaxError: Unexpected number
01.9 // SyntaxError: Unexpected number
09.9 // 9.9
(function(){"use strict"; 01;})() // SyntaxError: Octal literals are not allowed in strict mode.
(function(){"use strict"; 01.0;})() // SyntaxError: Unexpected number
(function(){"use strict"; console.log(09.9);})() // 9.9
Firefox 26
01.0 // SyntaxError: missing ; before statement
09.0 // SyntaxError: missing ; before statement
09.9 // 9.9
(function(){"use strict"; 01;})() // SyntaxError: octal literals and octal escape sequences are deprecated
(function(){"use strict"; 01.0;})() // SyntaxError: octal literals and octal escape sequences are deprecated
(function(){"use strict"; 09.9;})() // SyntaxError: octal literals and octal escape sequences are deprecated
In C type languages integer can be represented in multiple ways:
Each of these parseInt will convert to decimal base, so your octal base number is converted to decimal.
You have to put the number into "number"! The parseInt() function parses a string and returns an integer. Like this:
var example = parseInt("0000000101126");
console.log(example);