Numbers with zero start in Javascript

Asked

Viewed 289 times

6

I’m having a confusing problem, where I send a number 000214 by AJAX to a controller PHP, and there he arrives with result 140.

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

How could I pass the 000214 correctly to the controller?

  • Numbers with zero on the right are the octal notation, vc can remove the zeros directly in javascript and if you need them and the number is fixed you can padde in php.

  • If you give more details, I can improve the answer.

2 answers

9


I took a look at the w3schools and they mention so:

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.

Its 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 the function octdec php which converts the number from octal to decimal.

octdec("140") //deve retornar o seu número 214 sem os zeros que o precedem
  • in case I would even need to pass the 000214 the way it is because it is part of a compound code, and its string solution worked, since I do not need to do operations with this, being sent as "000214" in the case

7

If it is number, pass 214 (without zeros). Numbers starting at 0 use octal notation, not decimal. 214 written in octal equals 140 written in decimal, so you see one thing that 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, it is possible to indicate that this number is decimal and then the interpretation can be expected. Example in MDN documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.