Formatting Hex in Javascript

How can I format a hexadecimal number that will always be displayed with 4 digits in javascript?

For example, I will convert the decimal to hexadecimal:

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

I can successfully convert "23" to the hexadecimal value of "17". However, I would like to format it as "0017" (with four digits - adding 0 to 17).

All information will be greatly appreciated.

+4
source share
2 answers

Here is an easy way:

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

Or:

return ("0000" + (+d).toString(16)).slice(-4);
+9
source

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

I haven't tried it yet, but something like this should work:

sprintf("%.4X", d)
0

All Articles