DEV Community

Nenncy Finch
Nenncy Finch

Posted on • Updated on

Convert decimal to hexadecimal

Nowadays Javascript is not just limited to web development, many libraries are great for machine learning, deep learning, and IoT app development. For one of my recent projects, I had to create a decimal to hexadecimal converter. Honestly, I had no idea about such a converter. I did my research and spent my whole Sunday learning this.

For that reason, I’m sharing here code to convert decimal to hexadecimal so that you can use this code to create a converter.

Where did I use this converter?

I had to create a decimal to the hexadecimal translator for the machine learning project. My client wanted to enhance the security of the app so he encouraged me to convert the decimal numbers into the hexadecimal. And as I said above, I learned about all the numbering systems on Sunday and then built the tool.

What are decimal and hexadecimal numbers?

A decimal number is a base-10 number that consists of 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. You use this numbering system in the daily routine life and it is the easiest number to read.

Hexadecimal numbers are the advanced version of binary numbers. Hexadecimal numbers are base-16 numbers and humans cannot read these numbers easily. For that reason, my client wanted me to first develop a decimal to hexadecimal converter for security reasons.
Here, I’m sharing the code for the translation.

  function dectohex() {
    var x = document.getElementById("text_value").value;
var dectohexo = x.toString(16).toUpperCase ();

document.getElementById("ans").innerHTML = dectohexo;
                }
Enter fullscreen mode Exit fullscreen mode

Above is the simple code for decimal to hexadecimal conversion. This code works for the
students and for those who are working on a small project. However, it does not work for larger projects. This tool returns the correct answer for the numbers lesser than 11 characters. To get a correct answer for larger numbers you need to use a Javascript library called Bignumber.js. This library handles all the big number conversions.
Javascript code with the Bignumber library:

  function dectohex() {
    var x = document.getElementById("text_value").value;
        var xzc = new BigNumber(x, 10)
        var dectohexo = xzc.toString(16).toUpperCase ();

document.getElementById("ans").innerHTML = dectohexo;
                }
Enter fullscreen mode Exit fullscreen mode

That’s it! Done! You have developed your decimal to hexadecimal converter in Javascript. You can just copy and paste the above code and use it to develop your converter. If you have developed such a converter with any other technique then do let us know by dropping a comment.

Top comments (0)