Returned value is being the same as the entered value

Asked

Viewed 40 times

0

I’m having trouble displaying the result in converting decimal to binary.

When I do so by defining 2020 in the decimal variable, returns the correct value that is 11111100100

var decimal = 2020;
var binario = decimal.toString(2);
alert(binario);
//retorna 11111100100

However, when I use HTML input, the result is not as expected. It always returns the same value as I type in the input.

<input type="text" id="decimal-input">
<input type="button" value="CONVERTER" onclick="convertDec()">

function convertDec() {
   var decimal = document.getElementById('decimal-input').value;
   var binario = decimal.toString(2);
   alert(binario);
   //retorna sempre o mesmo valor que foi digitado no input do ID decimal-input, e não retorna no formato binário
}

Where am I going wrong?

2 answers

0


The attribute value of a input type="text" is a string, so first you must convert it to number.

As you want a whole number, use parseInt:

function convertDec() {
    var decimal = parseInt(document.getElementById('decimal-input').value);
    if (isNaN(decimal)) {
        alert("não foi digitado um número");
    } else {
        var binario = decimal.toString(2);
        alert(binario);
    }
}
<input type="text" id="decimal-input">
<input type="button" value="CONVERTER" onclick="convertDec()">

If a valid integer number is not entered, parseInt returns NaN (not-a-number), which can be verified with isNaN.

Still remembering that there is that corner case.

  • Thanks, it helped a lot !!

0

You need to convert the value you received into the input to Number. This can be done using parseInt() or Number(). Would look like this:

var decimal = parseInt(document.getElementById('decimal-input').value);

Your code was showing the same value because the variable type decimal is String. When you call the toString function in a String, it returns the same value.

  • Thanks, it helped a lot !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.