How to Convert Decimal to Hexadecimal in JavaScript

To convert a decimal number to its hexadecimal equivalent in JavaScript, you can use the “toString()” method of the Number object and pass “16” as the “radix” parameter.

Example

const decimalNumber = 255;
const hexNumber = decimalNumber.toString(16);

console.log(hexNumber);

Output

ff

In this above code, the decimal 255 is converted to its hexadecimal equivalent using the toString() method with a radix of 16. The resulting hexadecimal number ff is then logged to the console.

The resulting hexadecimal number is in lowercase, but you can easily convert it to uppercase using the toUpperCase() method of the String object, like this:

const decimalNumber = 255;
const hexNumber = decimalNumber.toString(16);

console.log(hexNumber.toUpperCase());

Output

FF

You can see that it will output the hexadecimal number in uppercase format.

Leave a Comment