在 .Net 中用零开始填充数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/489466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 11:06:52  来源:igfitidea点击:

Pad a number with starting zero in .Net

.netstringformattingpadding

提问by Alex

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 -> 01、2 -> 02 等)

回答by Rockcoder

number.ToString().PadLeft(2, '0')

回答by bdukes

I'd call .ToStringon the numbers, providing a format stringwhich requires two digits, as below:

我会在数字上调用.ToString,提供一个需要两位数字的格式字符串,如下所示:

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);

回答by MrTelly

Assuming you're just outputing these values, not storing them

假设您只是输出这些值,而不是存储它们

int number = 1;
Console.Writeline("{0:00}", number);

Here's a useful resourcefor all formats supported by .Net.

这是.Net 支持的所有格式的有用资源

回答by Taylor Brown

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:

在 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)

回答by doer

# 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!"