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
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.
const decimal = parseInt("ff", 16);
console.log(decimal); // 255
const hex = (255).toString(16).toUpperCase();
console.log(hex); // "FF"
const value = 255;
const text = "0x" + value.toString(16);
console.log(text); // "0xff"
console.log(parseInt("0xff", 16)); // 255
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);
}
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 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"
console.log((12).toString(2)); // "1100"
console.log((12).toString(8)); // "14"
See number base conversion, parseInt(), and numeric input validation.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.