Convert Hex to Decimal in JavaScript
Table of Contents
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:
JAVASCRIPTconst 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.
JAVASCRIPTparseInt(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.
JAVASCRIPTconst hexToDecimal = hex => parseInt(hex, 16);
Let's test our function:
JAVASCRIPTconst 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.
- Getting Started with TypeScript
- Getting Started with Express
- Getting Started with Electron
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Using Axios to Pull Data from a REST API