001
001

Reputation: 65205

Add zero-padding to a string

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

Upvotes: 195

Views: 250418

Answers (6)

feca
feca

Reputation: 1

with sed

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

Upvotes: 0

Noor E Alam Robin
Noor E Alam Robin

Reputation: 286

int num = 1;
num.ToString("0000");

Upvotes: 5

Shiraj Momin
Shiraj Momin

Reputation: 695

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

Upvotes: 43

Rex M
Rex M

Reputation: 144202

myInt.ToString("D4");

Upvotes: 75

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

"1".PadLeft(4, '0');

Upvotes: 11

kemiller2002
kemiller2002

Reputation: 115538

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

Upvotes: 370

Related Questions