Search code examples
javascripthex

Formatting Hex in Javascript


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.


Solution

  • Here is an easy way:

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

    Or:

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