0

I am making a javascript tool to convert decimal number value to HEX.

setInterval(
function tohex() {
var decimal = document.getElementById('result').value;
var hex = decimal.toString(16).toUpperCase();
  document.getElementById("hex").value = hex;
});
<input type='text' id="result" size="4" placeholder="Decimal" value="44032"/>
<input type="text" id="hex" oninput="tohex()" size="4" placeholder="HEX"/>

When var decimal = 44032;, the snippet shows the correct result: AC00. The value of the text input is 44032 as well, but in this case the script does not seem to render the correct hex value. What is the problem here, and how should I edit the script to render the 'correct' result?

Henry
  • 154
  • 10
  • 1
    `document.getElementById('result').value` always returns a string, not a number. Calling `.toString()` on a string is a no-op and just returns the initial value. – VLAZ Jan 06 '21 at 12:50

2 Answers2

1

Use parseInt. document.getElementById('result').value returns a value of string type. toString(16)function expects a number. Ref Number.prototype.toString()

var decimal = parseInt(decimal).toString(16).toUpperCase();

setInterval(
function tohex() {
var decimal = document.getElementById('result').value;
var hex = parseInt(decimal).toString(16).toUpperCase();
  document.getElementById("hex").value = hex;
});
<input type='text' id="result" size="4" placeholder="Decimal" value="44032"/>
<input type="text" id="hex" oninput="tohex()" size="4" placeholder="HEX"/>
Amaresh S M
  • 2,936
  • 2
  • 13
  • 25
1

Convert the value to number.

getElementById is returning the value of the element, which will be a string. You are operating directly with that value, intead you need to cast it to a number type variable first, you can do that using the operand +.

setInterval(
function tohex() {
  const decimal = +document.getElementById('result').value;
  const hex = decimal.toString(16).toUpperCase();
  document.getElementById("hex").value = hex;
});
<input type='text' id="result" size="4" placeholder="Decimal" value="44032"/>
<input type="text" id="hex" oninput="tohex()" size="4" placeholder="HEX"/>
Raul Sauco
  • 2,645
  • 3
  • 19
  • 22