Open In App

How to convert decimal to hex in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

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

Syntax:

decimalNumber.toString( radix )

Parameters:

  • decimalNumber: It holds the number in a decimal format that needs to be converted.
  • radix: It holds the base of the number system in which the number is converted.

Example 1: This example converts 20 to a hex number system. 

Javascript




let GFG_Var = 20;
 
function myGFG() {
    let GFG_Var2 = GFG_Var.toString(16);
 
    console.log("Hex of " + GFG_Var
        + " is = " + GFG_Var2);
}
 
myGFG();


Output

Hex of 20 is = 14

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

Javascript




let GFG_Var = 100;
 
function myGFG() {
    let GFG_Var2 = GFG_Var.toString(8);
     
    console.log("Octal of " + GFG_Var
        + " is = " + GFG_Var2);
}
 
myGFG();


Output

Octal of 100 is = 144

Last Updated : 20 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads