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
  • 32,014
  • 33
  • 141
  • 226

2 Answers2

4

How about

('00000'+(15).toString(16)).substr(-5)
exebook
  • 32,014
  • 33
  • 141
  • 226
CBroe
  • 91,630
  • 14
  • 92
  • 150
0

Maybe this:

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