How to convert decimal to hexadecimal in JavaScript ?

Here’s how to convert decimal numbers to hexadecimal in JavaScript, with multiple methods and examples:

1. Basic Conversion Using toString()

Convert a decimal number to hexadecimal (lowercase) using toString(16):

const decimal = 255;
const hex = decimal.toString(16); // "ff"

2. Uppercase Hexadecimal

Add .toUpperCase() for uppercase letters:

const hexUpper = decimal.toString(16).toUpperCase(); // "FF"

3. Handling Negative Numbers

Negative values are prefixed with -:

(-255).toString(16); // "-ff"

4. Add “0x” Prefix

Format as a hexadecimal literal:

const withPrefix = "0x" + decimal.toString(16); // "0xff"

5. Using Number.prototype.toString()

Works for numbers and numeric strings:

Number("123").toString(16); // "7b"

6. Rounding Decimal Fractions

Convert floating-point numbers:

Math.round(15.9).toString(16); // "10" (16 in hex)
(15.9).toString(16); // "f.e6666666666668" (exact representation)

7. Zero-Padded Hexadecimal

Pad with leading zeros to a specific length:

const paddedHex = decimal.toString(16).padStart(4, '0'); // "00ff"

8. Custom Conversion Function

For full control:

function decimalToHex(num, padLength = 0) {
  const hex = Math.round(num).toString(16);
  return hex.padStart(padLength, '0').toUpperCase();
}

decimalToHex(255, 4); // "00FF"

Examples

DecimalHexadecimal OutputMethod Used
0"0"(0).toString(16)
10"a"(10).toString(16)
255"ff"(255).toString(16)
-15"-f"(-15).toString(16)
3.14"3.23d70a3d70a3e"(3.14).toString(16)

Key Notes

  • Input Validation: Use Number() to handle non-number inputs:
  Number("123abc").toString(16); // NaN (handle with isNaN check)
  • Hexadecimal Range: Valid characters are 0-9 and a-f (or A-F).
  • Binary/Octal: Use toString(2) for binary or toString(8) for octal.

Choose the method based on whether you need uppercase letters, zero-padding, or error handling.

Leave a Reply

Your email address will not be published. Required fields are marked *