How To Convert Decimal To Hexadecimal In JavaScript?

A number is given and the task is to convert the number from decimal to hexadecimal. This can be done using the toString () method . It takes a parameter that is the base of the converted string. In this case, the base will be 16.

Syntax:

decimalNumber.toString( radix )

Parameters: It takes two parameters, which are listed below:

decimalNumber: contains the number in decimal format that you want to convert.
base: contains the base of the number system that the number is to be converted to.
Example 1: This example converts 20 to hexadecimal.

<!DOCTYPE html> 

<html> 

<head> 

    <title> 

        How to convert decimal to

        hex in JavaScript ?

    </title>

</head> 

<body style = "text-align:center;"> 

    <h1 style = "color:green;" > 

        Header

    </h1> 

    <p id="up"></p>

    <button onclick="Button()"> 

        Convert to hex

    </button> 

    <p id="down" style="color: green"></p>

    <script> 

        var Var = 20;

        var up = document.getElementById("up");

        up.innerHTML = Var;

        var down = document.getElementById("down");

        function Fnc() {

            var Var2 = Var.toString(16); 

            down = document.getElementById("down");

            down.innerHTML = "hex of "+ Var

                    + " is = " + Var2;
        }

    </script> 

</body> 

</html>  

Example 2: This example converts the number 100 to its octal number system.

<!DOCTYPE html> 

<html> 

    <head> 

        <title> 

            Decimal to octal number 

            system in JavaScript

        </title>

    </head> 

    <body style = "text-align:center;"> 


        <h1 style = "color:green;" > 

            Header

        </h1> 


        <p id = "up"></p>

        <button onclick="Button()"> 

            Convert to octal

        </button> 

        <p id = "down" style="color: green"></p>

        <script> 

            var Var = 100;

            var up = document.getElementById("up");

            up.innerHTML = Var;

            var down = document.getElementById("down");


            function Fnc() {

                var Var2 = GFG_Var.toString(8); 

                down = document.getElementById("down");

                down.innerHTML = "octal of "+ Var 

                        + " is = " + Var2;

            }

        </script> 

    </body> 

</html> 

Recommended Articles