15

Possible Duplicate:
How can I create a Zerofilled value using JavaScript?

When I convert a # from base 10 to base 16 hex using JavaScript, it doesn't zero pad the number.

For example:

var myBaseTenNumber = 0;
myBaseTenNumber.toString(16);  // should be 00 but it's just 0

Any easy way to zero pad my number to be 2 digits in length?

Community
  • 1
  • 1

1 Answers1

22

Generally something like

If you know the length upfront you can just do (something like):

var temp = myBaseTenNumber.toString(16);
("00" + myBaseTenNumber.toString(16)).substring(2 - temp.length, 2);
Noon Silk
  • 54,084
  • 6
  • 88
  • 105
  • 11
    Remember you can use `.substr(-2)` for the last two digits. – Camilo Martin Apr 07 '13 at 09:32
  • 3
    I honestly do not agree with the 'duplicate' flag. This has a very neat and simple solution which is absolutely not related to the general padding problem. This would do for unsigned integers in any base, maxPad is the output string length. It clearly needs a check on the input number first, to see if it exceeds the max length once transformed ((Math.pow(base,maxPad) + number)).toString(base).slice(1, maxPad +1) – malber Jul 12 '13 at 09:29
  • 1
    Should the second line in the solution not be '("00" + myBaseTenNumber.toString(16)).substring(temp.length);' ? – akkishore Aug 20 '13 at 18:08
  • Shouldn't it be `temp.length` instead of `2 - temp.length`? – kaihowl Sep 27 '13 at 09:18
  • 12
    ("00" + x.toString(16)).slice(-2) – user239558 Oct 16 '13 at 15:07
  • 1
    @malber But this is identical to the second answer there. Just that there are 2 instead of 5 zeroes. – user202729 May 25 '18 at 06:50
  • Thanks for pointing this out @user202729 . So long has passed since I provided that answer/comment and I gotta admit I used to be much smarter than my present self. I hope I could help – malber Jun 19 '18 at 13:49
  • @user239558 has the cleanest solution here. No extra temporary, no length measurement, no subtraction. `slice` does the job for you. I recommend posting it as a separate answer. – Ingmar Jul 12 '23 at 12:58