Zero start numbers in JavaScript

3

I'm having a confusing problem, in which I send a 000214 by AJAX to a PHP controller, and there it arrives with result 140 .

I gave a simple console.log(000214); and the result in the JS itself was 140 .

How can I pass the 000214 correctly to the controller?

    
asked by anonymous 11.03.2016 / 14:53

2 answers

6

I took a look at the w3schools page and they mention it like this:

  

Never write a number with a leading zero (like 07).   Some JavaScript versions interpret numbers as octal if they are written with a leading zero.

Your number 000214 is being interpreted as the octal (base 8) of 214.

I would try to pass as octal and convert the number to base 10 on the server or pass as a string and convert the string to decimal on the server.

There is octdec function in php that converts the octal number to decimal.

octdec("140") //deve retornar o seu número 214 sem os zeros que o precedem
    
11.03.2016 / 15:00
4

If it is number, pass 214 (without the zeros). Numbers starting at 0 use octal rather than decimal notation. 214 written in octal is equivalent to 140 written in decimal, so you see one thing the computer understands to be another, since it follows the strict rule and does not use the initial intuition.

Depending on where it is used, you can indicate that this number is decimal and then the interpretation may be as expected. Example in MDN documentation .

    
11.03.2016 / 14:59