Convert Number to Hexadecimal in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 03 20211 min read

banner

Photo by Tamara Bellis

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 parenthesis 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, in other words 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're calling the toString method directly on the number literal, you have to wrap it in parenthesis.
index.js
// โœ… Use parenthesis 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 letter 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee