How to convert decimal to/from a hexadecimal number in javascript

Hexadecimal number, often known as a Hexa number, is a number with 16 digits. It is based on the Base 16 system, also called a hexadecimal numbering system.

Hexadecimal numerals in javascript include decimal numbers, 0-9 (base 10), and an additional six alphabets ranging from A to F. i.e 0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F.

Example 32F or 1f,2A is a hexadecimal number.

Decimal Numbers are numbers with a base of 10, i.e. numbers ranging from 0 to 9. An example of a decimal number is 78.

Learn how to convert decimal to hexadecimal in JavaScript in this quick tutorial.

How to convert decimal numbers to hexadecimal numbers in Javascript?

Number contains toString() method in javascript, convert a number with a given base. the base is 16 for Hexa, 8 for octal, and 2 for binary.


Here is a code for parsing decimal to Hexa decimal example.

let hexa1 = Number(12).toString(16);
let hexa2 = Number(1918).toString(16);
console.log(hexa1); // c
console.log(hexa2); // 77e

toString works with numbers or integers only.

This method does not work for a string of numbers.

let hexa1 = "12".toString(16);
let hexa2 = "1918".toString(16);
console.log(hexa1); //12
console.log(hexa2); //1918

How to parse hexadecimal numbers to decimal numbers in Javascript?

The Number type contains the parseInt method, Convert string into a number type.


parseInt(String, radix);

The string is a string of numbers to convert. radix is a base such as 2, 8,16, etc.

Here is a code for convert hexadecimal to decimal example

let hexa1 = "c";
let hexa2 = "77e";

var decimal1 = parseInt(hexa1, 16);
var decimal2 = parseInt(hexa2, 16);



In summary, Learn the following examples.

  • Convert decimal to hexadecimal number using toString() method
  • Convert hexadecimal to decimal numbers using parseInt() method