Add zero-padding to a string

C#StringPadding

C# Problem Overview


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

C# Solutions


Solution 1 - C#

You can use PadLeft

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

Solution 2 - C#

myInt.ToString("D4");

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

with sed

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question001View Question on Stackoverflow
Solution 1 - C#kemiller2002View Answer on Stackoverflow
Solution 2 - C#Rex MView Answer on Stackoverflow
Solution 3 - C#Shiraj MominView Answer on Stackoverflow
Solution 4 - C#Matthew FlaschenView Answer on Stackoverflow
Solution 5 - C#Noor E Alam RobinView Answer on Stackoverflow
Solution 6 - C#fecaView Answer on Stackoverflow