Convert Number to Hexadecimal in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert Number to Hexadecimal in JavaScript #

To convert a number to hexadecimal, call the toString() method on the number, passing it 16 as the base, e.g. num.toString(16). The toString method takes the base as a parameter and returns the string representation of the number.

index.js
const num = 42; // ✅ Convert to Hex const hex = num.toString(16); console.log(hex); // 👉️ "2a" // ✅ Parse back to number const parsed = parseInt(hex, 16); console.log(parsed); // 👉️ 42 // ✅ Use parentheses when calling toString directly const hex2 = (42).toString(16); console.log(hex2); // 👉️ "2a"

The only parameter we passed to the Number.toString method is the radix (the base for the conversion).

The hexadecimal numeral system uses 16 distinct symbols, so that's the base we should specify.

The symbols are:

  • "0" - "9" to represent values 0 to 9
  • "a" - "f" to represent values 10 to 15.

The toString() method formats the number and returns its string representation.

Note that if you call the toString method directly on the number literal, you have to wrap it in parentheses.
index.js
// ✅ Use parentheses when calling toString directly const hex2 = (42).toString(16); console.log(hex2); // 👉️ "2a" // ⛔️ SyntaxError: Identifier directly after number const hex3 = 42.toString(16);

When a base of greater than 10 is provided to the toString method, the letters of the alphabet indicate the numerals greater than 9. For hexadecimal numbers (base 16) - the letters a - f are used.

const hex1 = (10).toString(16); console.log(hex1); // 👉️ "a" const hex2 = (15).toString(16); console.log(hex2); // 👉️ "f"

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.