How to convert the number 010 to the string "010",

While executing some random expressions in the console, I just found that

010 + "" return 8 (even 011,0100 .. return results by looking at the octal number system)

What should I do if I want to convert the number 010 to the string "010" ? Not only for 010 , but for all similar numbers. I managed to find a similar explanation for here . But this does not explain how to convert it to the exact version of the string.

+5
source share
5 answers

Javascript 010 has an octal literal and converts to 8 in decimal literal. In fact, you should avoid this, since strict mode forbids its use.

It is not possible to distinguish between octal and decimal notation other than parsing a function :)

+6
source

Get the string first by calling the toString() method with a base number that is 8 in this case

 Number(010).toString(8); //outputs "10" 

it also works without wrapping in Number,

 010.toString(8); //outputs "10" 

use this method for padd 0 if you know the length of the original number

 function pad(n,digits){return n<Math.pow(10, digits) ? '0'+n : n} 

So

 pad(Number(010).toString(8),3); //3 is the number of digits 
+5
source

Use the following code:

 "0" + (010).toString(8) // "010" "0" + (0111).toString(8) // "0111" 

And a more general solution:

 function toStringOctal(number) { return "0" + number.toString(8); } toStringOctal(010) // return "010" 

But note that in strict mode, the octal notation 0<number> not allowed.

+3
source
 var num = 10; var string = "0" + num.toString(); console.log(string);//gives you "010" 

As mentioned in the comments on this post, it will not directly convert 010, but it will build a string. Not the most elegant solution.

+1
source

If you want to convert several similar numbers to strings, you can also create a simple function that will do the job when called:

 function convertSomething(number) { var string = "" + number; return string } 

Then you can just call your conversion function when you need it.

+1
source

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


All Articles