w3docs logo
  1. Snippets
  2. JavaScript
  3. How to Convert Decimal to Hexadecimal in JavaScript

How to Convert Decimal to Hexadecimal in JavaScript

Sometimes, you may need to convert a number from decimal to hexadecimal. It is done with the toString() method. This method takes the parameter, which is the base of the converted string. The base is 16. In this tutorial, we will show you how simple can be converting decimal number to hexadecimal in JavaScript.

Convert a number to a hexadecimal string:

w3docs logo Javascript convert a number to a hexadecimal
let number = 4579; let hexStr = number.toString(16); console.log(hexStr);

The reverse will be done like this:

w3docs logo Javascript convert a number to a hexadecimal
let hexStr = '12ab'; let number = parseInt(hexStr, 16); console.log(number);

Decimal and Hexadecimal Number

The decimal number system has only ten digits from 0 to 9. Each value represents 0,1,2,3,4,5,6, 7,8 and 9 in this number system. The base is 10, as it has only ten digits.

The Hex number system has sixteen alphanumeric values from 0 to 9 and A to F. Each value represents 0,1,2,3,4,5,6, 7,8,9, A, B, C, D, E, and F in this number system. The base of the hex system is 16, as it has 16 alphanumeric values.

Do you find this helpful?