# How to Convert Decimal to Hexadecimal in JavaScript

Hexadecimal (hex) is a numbering system widely used in computer science and programming. While decimal is the most common numbering system used by humans, hexadecimal is frequently used for representing memory addresses, color codes, and binary data. In JavaScript, converting decimal numbers to hexadecimal can be accomplished using a few simple steps. In this article, we will explore different methods to convert decimal numbers to hexadecimal using JavaScript, along with code examples.

## Method 1: Using the toString() Method

The toString() method in JavaScript allows us to convert a decimal number to its equivalent hexadecimal representation. By passing the radix value of 16 as an argument to the toString() method, we can convert the decimal number to hexadecimal. Here's an example:

``````
// Method 1: Using the toString() method
function decimalToHex(decimal) {
return decimal.toString(16);
}
// Example usage
const decimalNumber = 255;
``````

## Method 2: Using the Number.prototype.toString() Method

Similar to the first method, we can also use the Number.prototype.toString() method to convert decimal numbers to hexadecimal. By specifying the radix value of 16, we achieve the desired conversion. Here's an example:

``````
// Method 2: Using the Number.prototype.toString() method
function decimalToHex(decimal) {
return decimal.toString(16);
}
// Example usage
const decimalNumber = 1234;
``````

## Method 3: Using the PadStart() Method

In some cases, you may want to ensure that the resulting hexadecimal representation has a fixed length, padding it with leading zeroes if necessary. We can achieve this by using the padStart() method. Here's an example:

``````
// Method 3: Using the padStart() method
function decimalToHex(decimal, length) {
}
// Example usage
const decimalNumber = 42;
``````

In the example above, we pass the desired length of the resulting hexadecimal representation as a parameter to the `decimalToHex()` function. The `padStart()` method ensures that the output has the specified length by padding it with leading zeroes.

Published on May 30, 2023

Tags: JavaScript

### Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

## Tutorials

### Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.