Decimal to binary

by trentHarlem

HTML

<h2>
 Decimal to Binary
</h2>
<label for='userInput'>Type a number here:</label>
<input id='userInput' type='text'/>
<br><br>
<button id='button' type='submit'>
 then Click this
</button>
<p id='display'>
</p>

JavaScript

const display = document.getElementById('display')
const userInput = document.getElementById('userInput')
const button = document.getElementById('button')


function decimalToBinary(decimal) {
  decimal = userInput.value || decimal
  let binary = "";
  while (decimal > 0) {
    binary = (decimal % 2) + binary;
    decimal = Math.floor(decimal / 2);
  }
  //  display.innerHTML = binary
  display.innerHTML = binary.padStart(8, '0')

  return binary;
}


function binaryToDecimal(binary) {
  let decimal = 0;
  for (let i = binary.length - 1, j = 0; i >= 0; i--, j++) {
    decimal += binary[i] * Math.pow(2, j);
  }
  return decimal;
}

button.addEventListener('click', decimalToBinary);

const decimal = 42;
const binary = "101010";

console.log(decimalToBinary(decimal)); // Output: "101010"
console.log(binaryToDecimal(binary)); // Output: 42

console.log(decimalToBinary(96)); // "1100000"
console.log(decimalToBinary(-6)); // "" ¡¡ FAIL !!