Binary to Decimal
by trentHarlem
HTML
<h2>
Binary to Decimal
</h2>
<label for='userInput'>Type a binary string 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 binaryToDecimal(binary) {
binary = userInput.value || binary
let decimal = 0;
for (let i = binary.length - 1, j = 0; i >= 0; i--, j++) {
decimal += binary[i] * Math.pow(2, j);
}
display.innerHTML = decimal
return decimal;
}
button.addEventListener('click', binaryToDecimal);