I have a requirement to pad all single digits numbers with a starting zero. Can some one please suggest the best method? (ex 1 -> 01, 2 -> 02, etc)
Asked
Active
Viewed 5.7k times
5 Answers
78
number.ToString().PadLeft(2, '0')

Rockcoder
- 8,289
- 3
- 32
- 41
-
11Upvoted because this solution is self-documenting -- clearer in its intent than a format provider ("00"). – Tim May 14 '12 at 18:45
66
I'd call .ToString on the numbers, providing a format string which requires two digits, as below:
int number = 1;
string paddedNumber = number.ToString("00");
If it's part of a larger string, you can use the format string within a placeholder:
string result = string.Format("{0:00} minutes remaining", number);

bdukes
- 152,002
- 23
- 148
- 175
6
Assuming you're just outputing these values, not storing them
int number = 1;
Console.Writeline("{0:00}", number);
Here's a useful resource for all formats supported by .Net.

MrTelly
- 14,657
- 1
- 48
- 81
3
I'm gonna add this option as an answer since I don't see it here and it can be useful as an alternative.
In VB.NET:
''2 zeroes left pad
Dim num As Integer = 1
Dim numStr2ch As String = Strings.Right("00" & num.ToString(), 2)
''4 zeroes left pad
Dim numStr4ch As String = Strings.Right("0000" & num.ToString(), 4)
''6 zeroes left pad
Dim numStr6ch As String = Strings.Right("000000" & num.ToString(), 6)

Taylor Brown
- 1,689
- 2
- 17
- 33
-1
# In PowerShell:
$year = 2013
$month = 5
$day = 8
[string] $datestamp = [string]::Format("{0:d4}{1:d2}{2:d2}", $year, $month, $day)
Write-Host "Hurray, hurray, it's $datestamp!"

doer
- 661
- 7
- 5