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 :

Community
  • 1
  • 1
Cheng.Lee
  • 186
  • 2
  • 11

3 Answers3

2

Please try this.

var bin = 1111;
var dec = parseInt(bin, 2);
var tostr= dec.toString(2)
SuperNova
  • 25,512
  • 7
  • 93
  • 64
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
Kypaz
  • 411
  • 3
  • 11
0
 var bin = 1111;
 var str = bin + '';
 console.log(str)

 // Pls try  working perfectly 
Sachin
  • 963
  • 11
  • 31
Mohammad shaban
  • 251
  • 2
  • 11
  • -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. – Hans Roerdinkholder Apr 08 '16 at 10:15