Add zero-padding to a string
Asked Answered
L

6

191

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
Lightproof answered 26/6, 2010 at 4:14 Comment(0)
N
365

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');
Natalia answered 26/6, 2010 at 4:18 Comment(3)
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 :-)Kinematograph
@paxdiablo: They were until the smiley.Gothic
"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');Passport
A
75
myInt.ToString("D4");
Abrasive answered 26/6, 2010 at 4:20 Comment(2)
The question is how to add padding "to a string."Experimentalize
string.Format("{0:D4}", myInt)Nephelometer
O
43
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

Oleoresin answered 1/11, 2012 at 10:1 Comment(0)
E
11
"1".PadLeft(4, '0');
Experimentalize answered 26/6, 2010 at 4:19 Comment(0)
C
5
int num = 1;
num.ToString("0000");
Chlodwig answered 19/9, 2019 at 6:4 Comment(0)
S
0

with sed

  • always add three leading zeroes
  • then trim to 4 digits
sed -e 's/^/000/;s/^0*\([0-9]\{4,\}\)$/\1/'
Saxtuba answered 19/11, 2021 at 6:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.