How to convert a number to hexadecimal format and vice-versa in JavaScript?

March 16, 2021 - 1 min read

Convert Number to Hexadecimal string

To convert a number to a hexadecimal string, you can use the toString() number method and pass 16 as the argument to the method in JavaScript.

const num = 1234;

const hexaDecimalString = num.toString(16);

console.log(hexaDecimalString); // "4d2"
  • The toString() method returns the hexadecimal value as a string.
  • The argument 16 in the toString() method is the radix.

Convert Hexadecimal string to a Number

Now to convert a hexadecimal string to a number, you can use the parseInt() number method and pass the hexadecimal string as the first argument and also the value16 as the second argument to the method in JavaScript.

/* Convert Hexadecimal String to Number */

const hexaDecimalString = "4d2";

const num = parseInt(hexaDecimalString, 16);

console.log(num); // 1234
  • The parseInt() method returns the corresponding number value.
  • The second argument 16 in the parseInt() method is the radix.

See both examples live in JSBin.

That's it! 🌟

Feel free to share if you found this useful 😃.