Question

Convert Decimal to Hexadecimal in JavaScript

javascripthexnumber-formattingradix

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 0 through 9.
  • Hexadecimal is base 16 and uses digits 0 through 9 plus letters a through f.

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.”

Take Quiz

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:

const hex = (48879).toString(16).toUpperCase();
console.log(hex); // "BEEF"

For fixed-width values, such as a two-digit byte or a six-digit CSS color, use padStart:

const byte = 10;
const twoDigitHex = byte.toString(16).padStart(2, "0");

console.log(twoDigitHex); // "0a"

Step by Step Execution

Consider this example:

const decimal = 26;
const hex = decimal.toString(16);

console.log(hex);

Step by step:

  1. decimal is assigned the numeric value 26.
  2. decimal.toString(16) asks JavaScript to represent 26 in base 16.
  3. Hexadecimal has digits 0–9, then a for 10, b for 11, and so on.
  4. 26 equals one group of 16 plus 10 remaining.
  5. In hexadecimal, one group of 16 is 1, and 10 is a, so the result is the string "1a".
  6. console.log(hex) prints:
1a

Here is a padded CSS-style color component:

const red = 5;
const hexRed = red.toString(16).padStart(2, "0");

console.log(hexRed); // "05"

Without padStart, the result would be "5", which is valid hexadecimal but not the required two-character format for an RGB 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, 0 into #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 65 becoming 41 for the character A.

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(255, 165, 0)); // "#ffa500"
Take Quiz

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 toString(16).
  • Small helper functions: Centralize padding and uppercase/lowercase choices rather than duplicating them.
  • Fixed widths: Use two digits for bytes (00–ff) and six digits for standard RGB colors (000000–ffffff).
  • Bitwise values: Convert masks and flags for logs, often with a 0x prefix.
const permissions = 31;
console.log(`Permissions mask: 0x${permissions.toString(16)}`);
// Permissions mask: 0x1f

For integers larger than JavaScript's safe Number range, use BigInt rather than Number:

const largeValue = 9007199254740993n;
console.log(largeValue.toString(16)); // "20000000000001"

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.log(decimal.toString(16)); // "ff"
}

Forgetting that hexadecimal letters are lowercase by default

console.log((255).toString(16)); // "ff"

Use .toUpperCase() if a format requires FF.

Omitting leading zeroes

A byte should normally have two hex digits. This is incomplete for byte-oriented formats:

const value = 10;
console.log(value.toString(16)); // "a"

Fix it with padding:

console.log(value.toString(16).padStart(2, "0")); // "0a"

Using parseInt for decimal-to-hex conversion

parseInt parses text into a number. It is mainly useful for converting from a string representation in a known base:

const decimal = parseInt("ff", 16);
console.log(decimal); // 255

To go in the other direction, use toString(16).

Converting fractional values unintentionally

console.log((10.5).toString(16)); // "a.8"

JavaScript can format fractions in hexadecimal, but many tasks—such as colors and bytes—require integers. Check with Number.isInteger(value) when appropriate.

Comparisons

TaskRecommended JavaScript operationExampleResult
Decimal number to hexadecimal textnumber.toString(16)(255).toString(16)"ff"
Hexadecimal text to decimal numberparseInt(text, 16)parseInt("ff", 16)255
Decimal text to a numberNumber(text)Number("255")255
Add a minimum number of digitspadStart(width, "0")"f".padStart(2, "0")"0f"
Use uppercase hex letterstoUpperCase()"ff".toUpperCase()"FF"

toString(16) is a formatting conversion: it writes a number in base 16. parseInt(value, 16) is a parsing conversion: it reads base-16 text and produces a number.

Also note the difference between a hexadecimal literal and conversion:

const value = 0xff; // JavaScript source code written in hexadecimal
console.log(value); // 255

console.log(value.toString(16)); // "ff"

Both refer to the same numeric value; the second line creates its hexadecimal string representation.

Take Quiz

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.isInteger(value)) {
  throw new TypeError("Expected an integer");
}

Rules to remember:

  • The radix for hexadecimal is 16.
  • toString(16) returns a string.
  • Hexadecimal digits use a–f by default.
  • Use padStart when a fixed number of digits is required.
  • Use BigInt for exact integer values beyond Number.MAX_SAFE_INTEGER.

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?

Use parseInt with radix 16:

const decimal = parseInt("ff", 16); // 255

Why does 10 become "a" instead of "0a"?

toString(16) does not add padding. Use padStart(2, "0") when you need exactly two digits.

Can JavaScript convert negative numbers to hexadecimal?

Yes, but the output includes a minus sign:

console.log((-26).toString(16)); // "-1a"

For byte, color, and bit-mask formats, validate that values are non-negative and within the expected range.

Take Quiz

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 0 through 255.
  • Convert each channel to a two-character hexadecimal string.
  • Return a color string beginning with #.
  • Throw an error when any channel is invalid.
Take Quiz

Keep learning

Related questions

View more