1

For example : input:0010 [number] output: 0010 [string]

I know the 0010 in JavaScript will be regarded as octal, so is it possible to code a function to convert it to string? The similar questions on stackoverflow had said how to convert known number of the leading zero input , but I haven't found any solution for unknown zero number input.

Similar questions :

0

3 Answers 3

2

Please try this.

var bin = 1111;
var dec = parseInt(bin, 2);
var tostr= dec.toString(2)
Sign up to request clarification or add additional context in comments.

2 Comments

This also can not work . Because input a number with leading zero will be treated octal . Try the 0111 ,will got NaN
In that case, you could convert using parseInt('0111')
0

If you know the wanted size for your output string, you can do this :

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
 return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

var outputString = pad(0010.toString(8),4); // 4 is the length of your output string

Comments

0
 var bin = 1111;
 var str = bin + '';
 console.log(str)

 // Pls try  working perfectly 

1 Comment

-1: this is not a solution, because var bin is the number 'elevenhundredandeleven', not the binary representation for 15 as you implicitly claim it to be.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.