4

How can I format a hex to be displayed always with 4 digits in javascript?

For example, I converting a decimal to hex :

port = 23
function d2h(d) {return (+d).toString(16);}
d2h(port)

I am successfully able to convert "23" to the hex value "17". However, I would like to be formatted like this "0017" (with four digits -- appending 0's before the 17).

All information would be greatly appreciated.

Omar Santos
  • 107
  • 1
  • 2
  • 5

2 Answers2

12

Here is an easy way:

return ("0000" + (+d).toString(16)).substr(-4);

Or:

return ("0000" + (+d).toString(16)).slice(-4);
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
0

You can use sprintf http://www.diveintojavascript.com/projects/javascript-sprintf

I havent tried it yet but something like this should work:

sprintf("%.4X", d)
PGJ
  • 126
  • 4