How to Pad A String With Leading Zeroes

By Peter Bromberg

There are many situations where a value needs to occupy a certain number of characters, but must be padded with leading zeroes for storage. Here is a Func to do this:

Func<string, int, string> PadStringToSize = (x,y) => (x.Length < y ? x.PadLeft(y, '0') : x);

You can then do things like:

Console.WriteLine(PadStringToSize("10000", 10)); // Pads to 10
Console
.WriteLine(PadStringToSize("10000", 30)); // Pads to 30

How to Pad A String With Leading Zeroes  (1887 Views)