185

How do I add "0" padding to a string so that my string length is always 4?

Example

If input "1", 3 padding is added = 0001
If input "25", 2 padding is added = 0025
If input "301", 1 padding is added = 0301
If input "4501", 0 padding is added = 4501
bluish
  • 26,356
  • 27
  • 122
  • 180
001
  • 62,807
  • 94
  • 230
  • 350

6 Answers6

360

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');
kemiller2002
  • 113,795
  • 27
  • 197
  • 251
  • 23
    Keep in mind that `"12345".PadLeft(4,'0')` is _still_ "12345" - it won't truncate it. This doesn't detract from this answer by the way since it meets all the specs (there's something strangely satisfying about having an answer you upvoted chosen as the accepted one (though not as satisfying as having one of your own accepted of course), sort of like your son getting into the best school), just thought I'd mention it in case it reared its ugly head sometime in the future. Cripes, I hope those parentheses are balanced :-) – paxdiablo Jun 26 '10 at 04:49
  • 25
    @paxdiablo: They were until the smiley. – Paul Ruane Aug 17 '10 at 11:07
  • 1
    `"1.2".PadRight(4,'0')` also works for zero filling a string number such as "1.20". I can do this to truncate and fill a simple string number < 10000. `num = num.length > 4 ? num.Substring(0,4) : num.PadRight(4,'0');` – Dan Randolph Apr 14 '17 at 17:59
74
myInt.ToString("D4");
Rex M
  • 142,167
  • 33
  • 283
  • 313
41
string strvalue="11".PadRight(4, '0');

output= 1100

string strvalue="301".PadRight(4, '0');

output= 3010

string strvalue="11".PadLeft(4, '0');

output= 0011

string strvalue="301".PadLeft(4, '0');

output= 0301

Shiraj Momin
  • 665
  • 6
  • 8
11
"1".PadLeft(4, '0');
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
5
int num = 1;
num.ToString("0000");
0

with sed

  • always add three leading zeroes
  • then trim to 4 digits
sed -e 's/^/000/;s/^0*\([0-9]\{4,\}\)$/\1/'
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
feca
  • 1