Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Hex in Javascript [duplicate]

Tags:

javascript

hex

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.

like image 208
Omar Santos Avatar asked Dec 16 '22 05:12

Omar Santos


1 Answers

Here is an easy way:

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

Or:

return ("0000" + (+d).toString(16)).slice(-4);
like image 153
bfavaretto Avatar answered Feb 17 '23 00:02

bfavaretto