Question
How can you convert decimal number values to their hexadecimal representation in JavaScript?
Short Answer
You will learn how JavaScript represents numbers in different bases and how to convert a decimal integer to hexadecimal using Number.prototype.toString(16). You will also see how to validate input, add leading zeroes, and handle common formatting needs such as CSS color values.
Concept
JavaScript numbers are stored as numeric values, not permanently as decimal or hexadecimal. Decimal and hexadecimal are simply different ways to write the same number.
- Decimal is base 10 and uses digits
0through9. - Hexadecimal is base 16 and uses digits
0through9plus lettersathroughf.
For example, the decimal number 255 is written as ff in hexadecimal:
255 (base 10) = ff (base 16)
In JavaScript, use the toString(radix) method to create a string representation of a number in another base. Passing 16 tells JavaScript to use hexadecimal.
const hex = (255).toString(16);
console.log(hex); // "ff"
The result is a string, because it is formatted text rather than a different numeric type. This matters when you need to display a color, build an identifier, write a byte sequence, or send formatted data to another system.
Mental Model
Think of a number as an amount of items, and a number system as the size of the boxes used to count them.
- Decimal uses boxes that hold 10 items.
- Hexadecimal uses boxes that hold 16 items.
The amount does not change; only the label used to describe it changes. A value of 255 is still the same amount whether you write it as 255 in decimal or ff in hexadecimal.
toString(16) is like asking JavaScript: “Write this number using groups of 16 instead of groups of 10.”
Syntax and Examples
Use number.toString(16) to convert an integer to a hexadecimal string.
const decimal = 48879;
const hexadecimal = decimal.toString(16);
console.log(hexadecimal); // "beef"
If you call the method directly on a numeric literal, wrap the literal in parentheses. Otherwise, JavaScript can mistake the first dot for part of a decimal number.
console.log((255).toString(16)); // "ff"
To include the conventional hexadecimal prefix, add 0x yourself:
const decimal = 255;
const hexWithPrefix = `0x${decimal.toString(16)}`;
console.log(hexWithPrefix); // "0xff"
By default, letters are lowercase. Convert the result when uppercase letters are required:
hex = ().().();
.(hex);
Step by Step Execution
Consider this example:
const decimal = 26;
const hex = decimal.toString(16);
console.log(hex);
Step by step:
decimalis assigned the numeric value26.decimal.toString(16)asks JavaScript to represent26in base 16.- Hexadecimal has digits
0–9, thenafor 10,bfor 11, and so on. 26equals one group of 16 plus 10 remaining.- In hexadecimal, one group of 16 is
1, and 10 isa, so the result is the string"1a". console.log(hex)prints:
1a
Here is a padded CSS-style color component:
Real World Use Cases
Decimal-to-hexadecimal conversion is useful whenever software needs a compact, base-16 text representation of integer values.
- CSS colors: Convert RGB values such as
255, 165, 0into#ffa500. - Binary and byte data: Display bytes from files, network packets, or hardware data as two-digit hexadecimal values.
- Debugging: Read memory addresses, bit masks, error codes, and flags, which are often shown in hexadecimal.
- IDs and hashes: Format numeric identifiers or segments of generated data in hex.
- Character codes: Inspect Unicode code points, such as
65becoming41for the characterA.
Example: convert an RGB color to a CSS hex color.
function rgbToHex(red, green, blue) {
const toHex = (value) => value.toString(16).padStart(2, "0");
return `#${toHex(red)}${toHex(green)}${toHex(blue)}`;
}
console.log(rgbToHex(, , ));
Real Codebase Usage
In production code, conversion is usually combined with validation and formatting rules. Do not assume external input is already a valid integer.
A reusable formatter can reject invalid values before converting them:
function decimalToHex(value, width = 0) {
if (!Number.isInteger(value)) {
throw new TypeError("Value must be an integer.");
}
if (value < 0) {
throw new RangeError("Value must not be negative.");
}
return value.toString(16).padStart(width, "0");
}
console.log(decimalToHex(15, 2)); // "0f"
console.log(decimalToHex(255, 6)); // "0000ff"
Common project patterns include:
- Validation at boundaries: Check API, form, or file input before calling .
Common Mistakes
Expecting a number instead of a string
toString(16) returns text:
const hex = (255).toString(16);
console.log(typeof hex); // "string"
This is correct. Use the string for display, serialization, or concatenation.
Calling toString(16) on a string input
This does not convert decimal text into hexadecimal:
const input = "255";
console.log(input.toString(16)); // "255"
Strings already have toString, but it ignores the radix. Convert the input to a number first and validate it:
const input = "255";
const decimal = Number(input);
if (Number.isInteger(decimal)) {
console.(decimal.());
}
Comparisons
| Task | Recommended JavaScript operation | Example | Result |
|---|---|---|---|
| Decimal number to hexadecimal text | number.toString(16) | (255).toString(16) | "ff" |
| Hexadecimal text to decimal number | parseInt(text, 16) | parseInt("ff", 16) | 255 |
| Decimal text to a number | Number(text) | Number("255") | 255 |
| Add a minimum number of digits |
Cheat Sheet
// Decimal integer -> lowercase hexadecimal string
const hex = decimal.toString(16);
// Numeric literal: use parentheses
const hex = (255).toString(16); // "ff"
// Add a 0x prefix
const hex = `0x${decimal.toString(16)}`;
// Uppercase letters
const hex = decimal.toString(16).toUpperCase();
// Two-digit byte
const byteHex = value.toString(16).padStart(2, "0");
// Six-digit value
const colorHex = value.toString(16).padStart(6, "0");
// Hexadecimal string -> decimal number
const decimal = parseInt("ff", 16); // 255
// Validate an integer before conversion
if (!Number.(value)) {
();
}
FAQ
How do I convert a decimal number to hexadecimal in JavaScript?
Call toString(16) on the number:
const hex = (255).toString(16); // "ff"
Does toString(16) return a number?
No. It returns a string because hexadecimal output is a textual representation of the number.
How do I add 0x to a hexadecimal value?
Prefix the converted string yourself:
const result = `0x${(255).toString(16)}`; // "0xff"
How do I make hexadecimal output uppercase?
Use toUpperCase() after conversion:
const hex = (255).toString(16).toUpperCase(); // "FF"
How do I convert "ff" from hexadecimal to decimal?
Mini Project
Description
Build a small RGB-to-hex color formatter. RGB colors are commonly represented as three decimal channel values from 0 to 255, while CSS also supports the hexadecimal form #rrggbb. This project combines decimal-to-hex conversion, input validation, and two-character padding.
Goal
Create a function that converts red, green, and blue decimal values into a valid six-digit CSS hexadecimal color string.
Requirements
- Accept three values: red, green, and blue.
- Require every value to be an integer from
0through255. - Convert each channel to a two-character hexadecimal string.
- Return a color string beginning with
#. - Throw an error when any channel is invalid.
Keep learning
Related questions
Abort Ajax Requests with jQuery jqXHR.abort()
Learn how to cancel an in-progress jQuery Ajax request with jqXHR.abort(), handle abort status safely, and avoid stale UI updates.
Access the Correct this Inside a JavaScript Callback
Learn why JavaScript this changes in callbacks and how to preserve an object context using bind, arrow functions, and event handler patterns.
Add Key-Value Pairs to JavaScript Objects
Learn how to add key-value pairs to JavaScript objects with dot and bracket notation, dynamic keys, examples, and common mistakes.