In this article, we'll explore two methods to convert decimal to hexadecimal in JavaScript. We'll discuss and provide code examples for each method.

Convert decimal to hexadecimal using toString() method

Converting decimal to hexadecimal using the toString() method is straightforward in JavaScript. Here's how you can do it:

<script>
 // Decimal number
 const decimalNumber = 255;
// Convert decimal to hexadecimal
 const hexadecimal = decimalNumber.toString(16);
// Output the hexadecimal value
 console.log("Hexadecimal:", hexadecimal); 
</script>
  1. Define a decimal number to convert.
  2. Use the toString() method with a base of 16 to convert the decimal number to hexadecimal.
  3. Output the hexadecimal value using console.log().

Using the Number.prototype.toString() Method

Another method to convert decimal to hexadecimal is by using the Number.prototype.toString() method. Here's how to do it:

<script>
 // Decimal number
 const decimalNumber = 255;
 // Convert decimal to hexadecimal
 const hexadecimal = (decimalNumber).toString(16);
 // Output the hexadecimal value
 console.log("Hexadecimal:", hexadecimal); 
</script>
  1. Define a decimal number to convert.
  2. Use the Number.prototype.toString() method with a base of 16 to convert the decimal number to hexadecimal.
  3. Output the hexadecimal value using console.log().

Conclusion

In this article, we explored two methods to convert decimal to hexadecimal in JavaScript. The first method utilizes the toString() method directly on the decimal number, while the second method uses the Number.prototype.toString() method.