3

When you convert a small number to a hexadecimal representation, you need leading zeroes, because toString(16) will return f for 15, instead of 00000f. Usually I will use the loop like this:

var s = X.toString(16); while (s.length < 6) s = '0' + s

is there a better way in JavaScript?

UPD: The answer suggested answer How can I create a Zerofilled value using JavaScript? is not what I am looking for, I look for a very short code, that is suited specifically for 24 bit integers converted to a hexadecimal looking strings.

Community
  • 1
  • 1
exebook
  • 29,722
  • 29
  • 120
  • 210

2 Answers2

3

How about

('00000'+(15).toString(16)).substr(-5)
exebook
  • 29,722
  • 29
  • 120
  • 210
CBroe
  • 86,812
  • 12
  • 88
  • 140
0

Maybe this:

var s = X.toString(16);
s = "000000".substr(0, 6 - s.length) + s;
user3146587
  • 4,160
  • 1
  • 15
  • 25