DEV Community

loading...

Convert Hexadecimal to Decimal Numbers in Javascript/Vue/Nuxt

dwayneosmith1 profile image Dwayne O. Smith Updated on ・2 min read

Different numbering systems are really interesting. Most of the electronic systems and microprocessors use binary numbers. For one of my recent projects, I worked with these numbering systems.

Honestly, I did not have in-depth knowledge about decimal, binary, octal and hexadecimal numbers. I found it difficult when I had to develop hexadecimal to decimal converter. I knew a little bit about binary numbers but I had absolutely no idea about decimal and hexadecimal numbers.

What is the Hexadecimal Number?

Hexadecimal numbers are also known as the bast-16 numbers, it contains 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Along with that, it also contains A-F letters. Hexadecimal numbers occupy a lot of memory but these numbers can be described in the least amount of digits. Hexadecimal numbers are used in modern flip-flops and the MAC address of every electronic device.

What is a Decimal number?

You might have studied a lot about decimal numbers in maths. Yes, that’s it! Decimal numbers contain 0 to 9. It is also one of the most popular numbers. After binary numbers, decimals are the most used electronic numbering system.

Why I had to develop a tool to convert hexadecimal to decimal?

As decimal numbers include just 0 to 9, it is a little bit difficult to read big numbers while hexadecimal numbers are base-16 and it is easy to read hexadecimal numbers.

Javascript code for Hexadecimal to decimal conversion:

function hextodec(){
var a = 16;
    var dectobin = a.toString(10);
document.getElementById("demo").innerHTML = dectobin;
}
Enter fullscreen mode Exit fullscreen mode

The above code works fine but it returns the wrong answer if a user inserts a number with a length above 16. To get the correct answer for the number length above 16, I used Bignumber.js. Below is the code with Bignumber.js.

Javascript/Vue.js/Nuxt code with Bignumber.js:

hextodec() {
    var x = new BigNumber(this.text_value, 16)
    var dectobin = x.toString(10);
    this.ans = dectobin;
     }
Enter fullscreen mode Exit fullscreen mode

I also had to develop a decimal to hexadecimal tool for the same project. Below is the Javascript/Vue/Nuxt code for the conversion:

var x = new BigNumber(this.text_value, 10)
    var dectobin = x.toString(16).toUpperCase ();
    this.ans = dectobin;
Enter fullscreen mode Exit fullscreen mode

In the above code as well, I used BugNumber library to get a correct answer for the bignumbers.

So, above is the simple code block for hexadecimal to decimal conversion. I hope this code helps you if you are working on a hex to decimal converter.

Discussion (0)

pic
Editor guide