问题
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)
回答1:
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);
回答2:
number.ToString().PadLeft(2, '0')
回答3:
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.
回答4:
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)
回答5:
# 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!"
来源:https://stackoverflow.com/questions/489466/pad-a-number-with-starting-zero-in-net