# How to Convert Decimal to Hexadecimal in JavaScript

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

The decimal number system has only ten digits from 0 to 9. Each value represents 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 in this number system. The base is 10, as it has only 10 digits.

The Hex number system has sixteen alphanumeric values from 0 to 9 and A to F. Each value represents 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F in this number system.

## Example 1: Using toString() method to convert decimal to hexadecimal

``````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.

## Example 2: Converting hexadecimal to uppercase

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.

## Example 3: Calling toString() method on number literal

Wrap a number literal in parentheses (( )) or use two dots(..) before using the toString() method.

``````const hex = (21).toString(16);
console.log(hex);

// Use double dots
const hex2 = 19..toString(16);
console.log(hex2);
``````

Output

``````15
13
``````

## Example 4: Convert RGB(A) to Hex

Converting decimal values to hex converts an RGB color code to its equivalent.

``````function decToHex(dec) {
return dec.toString(16);
}

}

function rgbToHex(r, g, b) {

return `#\${hexR}\${hexG}\${hexB}`;
}

console.log(rgbToHex(250, 255, 110));

console.log(rgbToHex(200, 100, 50));

console.log(rgbToHex(16, 8, 8));
``````

Output

``````#faff6e
#c86432
#100808``````

That’s it!