Decimal number to Hex value conversion

We can convert decimal to hexadecimal values in JavaScript by using toString() function. Here is the syntax

variable.toString(radix);

If radix is kept at 16 then the output will be in hexadecimal value. Here is an sample

var n1=12;
document.write (n1.toString(16));

The output of above string is c ( Hex value of 12 )
The input variable must be an integer. So we will use paraseInt() function to convert any input to pure integer value.

We will also use isNan function to check the user input.

Demo of converting any decimal value to Hex

Here is the script of this demo

<html>
<head>
<title>Demo of decimal to hexadecimal conversion</title>
<script language='JavaScript' type='text/JavaScript'>
<!--
function hex_convt(){
var n1=document.getElementById('t1').value;
if(isNaN(n1)){
document.getElementById("d1").innerHTML=document.getElementById('t1').value + " is not a number ";
}else{
n1=parseInt(n1);
document.getElementById("d1").innerHTML=n1.toString(16);
// Change the toString(16) to toString(8) or toString(2) get Octal and binary conversion
}

}
//-->
</script>

</head>
<body>

<input type=text name=t1 id='t1' size=8>
<input type=button name='SB' value='Change to Hex' onclick="hex_convt()";>
<div id=d1></div>
<br><br>
</body>
</html>


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer