How to Convert Decimal Values to Hexadecimal in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the toString()
Method
You can simply use the toString()
method with a radix or base of 16 to convert the decimal values to their hexadecimal equivalent in JavaScript. The radix
is an optional parameter specifying the base to use for representing numeric values; It must be an integer in the range 2 through 36.
Let's take a look at an example to understand how it basically works:
Example
Try this code »// Simple function to convert decimal to hexadecimal
function dec2Hex(dec) {
return Math.abs(dec).toString(16);
}
// Testing some values
console.log(dec2Hex(960)); // Output: 3c0
console.log(dec2Hex(255)); // Output: ff
console.log(dec2Hex(15)); // Output: f
Related FAQ
Here are some more FAQ related to this topic: