Javascript - leading zero to a number, converting a number to some other number. not understand why this is happening?

Rolling zero to a certain number, converting the number to some format of an unknown number. eg:

017 Converts to 15

037 converts to 31

It has also been found that numbers having 8 0r 9 at the end remain the same for example:

018 18

038 38

o59 59

one more thing i found is

for each subsequent range 10, the difference between the converted value and the actual value is increased by 2

eg:

for the range 00-09 difference is 0 ie the value 07 will be 7, 04 will be 4

for the range 010-019 difference 2 value 017 will be 15, 013 will be 11

for the range 020-029 difference 4 value 027 will be equal to 23, 021 will be equal to 17

etc.

here is a snap for the test http://jsfiddle.net/rajubera/BxQHF/

I do not understand why this is happening?

Please help me how to get the correct decimal number from a number with a zero number?

+4
source share
2 answers

If there is a leading 0, it converts it to octal (base 8), if it has a real number in base 8 (the number is not more than 7).

For instance:

017 at the base of 8 is 1 * 8 + 7 = 15 037 at the base of 8 is 3 * 8 + 7 = 31

018 converts to 18 because 018 not a valid number in base 8

Please note that the behavior with respect to the base, according to which the number is converted by default, may be browser specific, therefore it is important to always specify base / radix when using parseInt :

parseInt("017",10) === 17

UPDATE based on comments:

parseInt expects a string as the first argument, therefore

parseInt("012",10) === 12

+6
source

One reason for "use strict";

 (function() {"use strict"; 017})() // Firefox => SyntaxError: "0"-prefixed octal literals and octal escape sequences are deprecated; for octal literals use the \"0o\" prefix instead // Chrome, Node => SyntaxError: Octal literals are not allowed in strict mode. 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal

+1
source

Source: https://habr.com/ru/post/1494522/


All Articles