Computer >> Computer tutorials >  >> Programming >> Javascript

How to format hexadecimal Number in JavaScript?


Firstly convert your number to hexadecimal with leading zeros and then format it by adding dashes.

Example

You can try to run the following code to format hexadecimal number −

<!DOCTYPE html>
<html>
   <body>
      <script>
         var num = 32122;
         var myHex = ("000000000000000" + num.toString(16)).substr(-16);

         var resHex = myHex.substr(0, 8)+'-'+myHex.substr(8,4)+'-'+myHex.substr(12,4);
         document.write(resHex);
      </script>
   </body>
</html>

Output

00000000-0000-7d7a