Formatting hexadecimal Number to short UUID in JavaScript

ES6 Version

function toPaddedHexString(num, len) {
    str = num.toString(16);
    return "0".repeat(len - str.length) + str;
}

var hexStr = toPaddedHexString(12345, 16);

Further to knabar's answer:

If your number is really a full 64 bits long you should be aware that javascript has only doubles, which top out at around 53 bits of precision. E.g.

var i = 0x89abcdef01234567; // a 64-bit constant
var h = ("000000000000000" + i.toString(16)).substr(-16); // "89abcdef01234800"

So you probably want to split this into two 32-bit numbers, and format them 8 digits at a time. Then the second caveat strikes: javascript performs bitwise ops on signed 32-bit integers, and this formatting code can't handle negative numbers.

var i = 0xffd2 << 16; // actually negative
var h = ("0000000" + i.toString(16)).substr(-8); // "0-2e0000"

Since it's fairly likely that numbers you want formatted in hexadecimal are the result of bitwise manipulations, the code can be tweaked to print in two's complement instead:

var i = 0xffd2 << 16; // actually negative
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "ffd20000"

This produces the hex representation of the bottom 32 bits of the integral part of arbitrary positive and negative numbers. This is probably what you want (it's approximately printf("%08x")). Some more corner cases:

var i = 1.5; // non-integers are rounded
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "00000001"

var i = -1.5; // rounding is towards zero
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "ffffffff"

var i = NaN; // not actually a number
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "00000000"

I would do a two-step process:

1) convert number to 16 digit hex with leading zeros:

var i = 12345; // your number
var h = ("000000000000000" + i.toString(16)).substr(-16);

2) add dashes

var result = h.substr(0, 8)+'-'+h.substr(8,4)+'-'+h.substr(12,4);

There are two methods for String called padStart and padEnd

const num = 15;
console.log(num.toString(16).padStart(2, "0")); // "0f"
const num = 15;
console.log(num.toString(16).padEnd(2, "0")); // "f0"

Additional information on the link: padStart, padEnd