JavaScript How to Convert Decimal to Hexadecimal
Use the JavaScript method
number.toString(16) to convert a decimal number to its hexadecimal string representation.Examples
Input255
Output"ff"
Input16
Output"10"
Input0
Output"0"
How to Think About It
To convert a decimal number to hexadecimal, think of it as changing the number base from 10 to 16. JavaScript provides a simple way to do this by converting the number to a string in base 16 using
toString(16).Algorithm
1
Get the decimal number input.2
Call the <code>toString</code> method on the number with 16 as the argument.3
Return the resulting string which is the hexadecimal representation.Code
javascript
const decimalNumber = 255; const hexString = decimalNumber.toString(16); console.log(hexString);
Output
ff
Dry Run
Let's trace converting 255 to hexadecimal using toString(16).
1
Start with decimal number
decimalNumber = 255
2
Convert to hex string
hexString = (255).toString(16) => 'ff'
3
Output result
console.log(hexString) prints 'ff'
| Decimal Number | Hexadecimal String |
|---|---|
| 255 | ff |
Why This Works
Step 1: Using toString with base 16
The toString method converts a number to a string in the specified base, here base 16 for hexadecimal.
Step 2: Hexadecimal digits
Digits 10 to 15 are represented as letters a to f in the output string.
Step 3: Result is a string
The output is a string representing the hexadecimal number, which can be used or displayed as needed.
Alternative Approaches
Using Number.prototype.toString with uppercase
javascript
const decimalNumber = 255; const hexString = decimalNumber.toString(16).toUpperCase(); console.log(hexString);
This method converts to uppercase hex letters (A-F) instead of lowercase.
Using parseInt and toString for string input
javascript
const decimalString = '255'; const hexString = parseInt(decimalString, 10).toString(16); console.log(hexString);
This approach converts a decimal string to hex by parsing first, useful if input is a string.
Complexity: O(1) time, O(1) space
Time Complexity
Conversion using toString(16) is a constant time operation because it directly converts the number without loops.
Space Complexity
The space used is constant, only storing the resulting string representation.
Which Approach is Fastest?
Using toString(16) is the fastest and simplest method compared to manual conversion or parsing strings.
| Approach | Time | Space | Best For |
|---|---|---|---|
| toString(16) | O(1) | O(1) | Simple and fast conversion |
| toString(16).toUpperCase() | O(1) | O(1) | Uppercase hex output |
| parseInt + toString(16) | O(1) | O(1) | When input is a decimal string |
Use
number.toString(16) to quickly get a hexadecimal string from a decimal number.Forgetting that
toString(16) returns a string, not a number, which may affect further calculations.