Decimal and Hexadecimal Conversion in JavaScript

Convert a decimal Number to hexadecimal with number.toString(16). Convert hexadecimal text back to decimal with parseInt(text, 16).

console.log((12).toString(16));    // "c"
console.log(parseInt("c", 16));      // 12

Convert decimal to hexadecimal Top ↑

const n = 12;
const hex = n.toString(16);
console.log(hex); // "c"

The 16 is the radix. toString(radix) supports bases from 2 through 36.

Convert hexadecimal to decimal Top ↑

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

Return uppercase hexadecimal letters Top ↑

const hex = (255).toString(16).toUpperCase();
console.log(hex); // "FF"

Add or read a 0x prefix Top ↑

const value = 255;
const text = "0x" + value.toString(16);
console.log(text); // "0xff"
console.log(parseInt("0xff", 16)); // 255

Validate decimal input before conversion Top ↑

The original example used global isNaN() and parseInt(). For a decimal form field that must contain one complete numeric value, Number() plus Number.isInteger() gives stricter behavior.

function decimalToHex(raw) {
  if (raw.trim() === "") return null;
  const value = Number(raw);
  if (!Number.isInteger(value)) return null;
  return value.toString(16);
}

Validate an entire hexadecimal string Top ↑

parseInt() can stop at an invalid character and still return the prefix it already parsed. Use a pattern first when the whole string must be hexadecimal.

function hexToDecimal(raw) {
  const text = raw.trim().replace(/^0x/i, "");
  if (!/^[0-9a-f]+$/i.test(text)) return null;
  return parseInt(text, 16);
}

Hexadecimal values in web colors Top ↑

Hexadecimal is common in CSS color notation. Decimal RGB 0, 0, 255 corresponds to hexadecimal #0000FF. When generating a two-digit color component, pad values below 16 with a leading zero.

const blue = (255).toString(16).padStart(2, "0");
console.log(blue); // "ff"

Convert to binary or octal with the same method Top ↑

console.log((12).toString(2)); // "1100"
console.log((12).toString(8)); // "14"

See number base conversion, parseInt(), and numeric input validation.

JavaScript Math Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer