Skip to content

Padding integers with leading zeros in C#

Lately I’ve been working with a few RESTful APIs that accept date components (day, month, year) and some of them require that day and month parameters be two digits in length. So for example for February 9th, I would need to send “02” for the month and “09” for the day. Padding integers with leading zeros is super easy to do in C#, and here’s how:

DateTime feb9th2020 = new DateTime(2020, 2, 9);

var output = new[] {
	feb9th2020.Month.ToString(),
	feb9th2020.Month.ToString("00"),
	feb9th2020.Day.ToString(),
	feb9th2020.Day.ToString("00"),
	feb9th2020.ToString("MM/dd/yyyy")
};

Console.WriteLine(String.Join(Environment.NewLine, output));

Here’s the output:

2
02
9
09
02/09/2020

Note that .Month and .Day are integer types, but I’m using DateTime here to illustrate a real-world usage scenario. The highlighted lines show that you simply provide the number of zeros you want to pad to the ToString() method. More info and examples can be found here.

Published inTips & Tricks

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *