I'm working on a binary-to-decimal and decimal-to-binary converter in JavaScript and thought I'd try using Number.parseInt() to go about this. That said, my output keeps showing "NaN" instead of the desired conversion. Any assistance with this would be very much appreciated!
// Get binary number from user for decimal conversion
let binary = document.getElementById("binary").value;
// Set the base (radix) to 2 for decimal conversion
let binBase = 2;
// Get decimal number from user for binary conversion
let decimal = document.getElementById("decimal").value;
// Set the base (radix) to 10 for binary conversion
let decBase = 10;
// Function to convert binary to decimal
function getDecimal(binary, binBase) {
let finalDec = Number.parseInt(binary, binBase);
// Output the decimal number
document.getElementById("showDecimal").innerHTML = finalDec;
return finalDec;
}
// Function to convert decimal to binary
function getBinary(decimal, decBase) {
let finalBin = Number.parseInt(decimal, decBase);
// Output the binary number
document.getElementById("showBinary").innerHTML = finalBin;
return finalBin;
}
<html>
<head>
<meta charset="UTF-8">
<title>Binary to Decimal and Back Converter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Please Enter the Binary Number (Base 2) That You Would Like Converted to Decimal Form (Base 10)</h3>
Binary: <input type="text" id="binary" value="">
<button onclick="getDecimal()">Calculate</button>
The Decimal Number Is:
<p id="showDecimal"></p>
<h3>Please Enter the Decimal Number (Base 10) that You Would Like Converted to Binary Form (Base 2)</h3>
Decimal: <input type="text" id="decimal" value="">
<button onclick="getBinary()">Calculate</button>
The Binary Number Is:
<p id="showBinary"></p>
<script src="script.js"></script>
</body>
</html>
Picture of what it looks like in browser:
Thanks in advance for your help!