# Convert Number to Hexadecimal in JavaScript

Wed Nov 03 20211 min read

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
```Copied!```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
```Copied!```// โ 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.

```Copied!```const hex1 = (10).toString(16);
console.log(hex1); // ๐๏ธ "a"

const hex2 = (15).toString(16);
console.log(hex2); // ๐๏ธ "f"
``````