Convert Hex to Decimal in JavaScript

Updated onbyAlan Morel
Convert Hex to Decimal in JavaScript

Table of Contents

  1. parseInt()
  2. Conclusion

In this post, we'll learn how to convert hexadecimal numbers to decimal in JavaScript.

To do this, we will write a function that takes a hexadecimal string as an argument and returns its decimal representation.

For example, we want the following input to return the following output:

JAVASCRIPT
const hex1 = "2"; // Should return 2 const hex2 = "35"; // Should return 53 const hex3 = "1f4"; // Should return 500 const hex4 = "7b2"; // Should return 1970 const hex5 = "123abc"; // Should return 1194684

parseInt()

The best way to convert a hexadecimal number to decimal is to make use of the parseInt() function.

The parseInt() function takes a string as an argument and returns an integer.

JAVASCRIPT
parseInt(string, radix);

The first argument of it is the string to be converted, and the second argument is the radix (base) of the number.

Since we are converting to a hexadecimal number, the radix is 16, since there are 16 hexadecimal digits.

With this, we can create a function called hexToDecimal that takes a hexadecimal string and returns its decimal equivalent.

JAVASCRIPT
const hexToDecimal = hex => parseInt(hex, 16);

Let's test our function:

JAVASCRIPT
const hexToDecimal = hex => parseInt(hex, 16); const dec1 = hexToDecimal("2"); const dec2 = hexToDecimal("35"); const dec3 = hexToDecimal("1f4"); const dec4 = hexToDecimal("7b2"); const dec5 = hexToDecimal("123abc"); console.log(dec1); // 2 console.log(dec2); // 53 console.log(dec3); // 500 console.log(dec4); // 1970 console.log(dec5); // 1194684

Our function is working as intended, converting our hexadecimal numbers to decimal!

Conclusion

We've seen how you can use parseInt() in JavaScript to convert a hexadecimal number to decimal.

Hopefully, this post has been useful to you and you can use it to convert hexadecimal numbers to decimal in your own projects.

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.