var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var val = binaryValue.value;
var result = 0;
var i = val.length-1;
var j = 0;
while (i > -1) {
var y = (Number(val[i])) * (2 ** [j]);
result = y;
i--;
j ;
console.log(y);
}
decimalValue.value = result;
console.log(binaryValue.value);
}
Using the above codes I tried to obtain a value from an input field and do a calculation to convert it to a decimal number.But It doesn't obtain the input value.I tried several times and I am unable to figure out it.
CodePudding user response:
Have you added the script in project?? if not try to add script in the project it will work
CodePudding user response:
This is how you get a value from an input field:
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var NumValue = binaryValue.value
console.log("input value: " NumValue);
//this is how you convert a binary number to decimal
console.log("binary number: " (NumValue >>> 0).toString(2));
//this is how you convert an decimal number to binary
console.log("decimal number: " parseInt(NumValue, 2));
}
<input type="text" id="binary" placeholder="insert value"/>
<button type="button" onclick="binaryToDecimal()">Show value</button>
Use this example to fix your code.
I also added ways to convert to and from binary numbers.