-2

How can i convert decimal to binary?

Here is my js code:

while (decimal >= 2) {
    var dec2 = decimal;

    if (decimal % 2 == 0) {
      rests.push(0);
      decimal /= 2;
    } else {
      rests.push(1);
      decimal -= 1;
      decimal /= 2;
    }
  }
  rests.push(1);
  display.textContent = rests.join("");

I think it's too much is there anyway to do that in few lines of code?

  • 3
    Does this answer your question? [How to convert decimal to binary in JS?](https://stackoverflow.com/questions/26127192/how-to-convert-decimal-to-binary-in-js) – aerial Nov 10 '21 at 08:36

1 Answers1

0

Simplest way to do that -> Number(decimal).toString(2)