Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to convert decimal to hex in JavaScript?
Converting decimal numbers to hexadecimal is a fundamental programming task, especially in web development where hex color codes are widely used. JavaScript provides built-in methods and allows custom implementations for this conversion.
Using toString() method
Using Custom Function
Using the toString() Method
The toString() method converts a number to its string representation in the specified base. Every JavaScript number has this method available.
Syntax
Number.toString(radix)
Parameters
radix (optional): An integer between 2 and 36 specifying the base. For hexadecimal conversion, use 16.
Return Value
Returns a string representation of the number in the specified base.
Example
Converting decimal numbers to hexadecimal using the toString() method:
<html>
<body>
<h2>Convert decimal to hex using toString() method</h2>
<p id="input">Decimal: </p>
<p id="output">Hex: </p>
<script>
let num = 146541;
document.getElementById("input").innerText += num;
let hex = num.toString(16).toUpperCase();
document.getElementById("output").innerText += hex;
</script>
</body>
</html>
Decimal: 146541 Hex: 23C6D
Using Custom Logic
You can implement custom logic to understand the conversion process better. This method uses division and remainder operations to extract hexadecimal digits.
Algorithm Steps
Create a string containing all hex characters: "0123456789ABCDEF"
Divide the decimal number by 16 repeatedly
Use the remainder to find the corresponding hex character
Build the result string from right to left
Example
Converting decimal to hex using a custom function:
<html>
<body>
<h2>Convert decimal to hex using custom logic</h2>
<p id="input">Decimal: </p>
<p id="output">Hex: </p>
<script>
let num = 116565;
document.getElementById("input").innerText += num;
let hexChars = "0123456789ABCDEF";
let result = "";
let temp = num;
// Handle special case for 0
if (num === 0) {
result = "0";
} else {
while (num > 0) {
let remainder = num % 16;
result = hexChars[remainder] + result;
num = Math.floor(num / 16);
}
}
document.getElementById("output").innerText += result;
</script>
</body>
</html>
Decimal: 116565 Hex: 1C755
Comparison
| Method | Code Complexity | Performance | Use Case |
|---|---|---|---|
toString(16) |
Simple | Fast | Production code |
| Custom Logic | Complex | Slower | Educational purposes |
Conclusion
The toString(16) method is the preferred approach for converting decimal to hexadecimal in JavaScript due to its simplicity and efficiency. Custom logic helps understand the underlying conversion process.
