数字格式:如何将1转换为"01",将2转换为"02"等?

joh*_*ner 38 c#

我有像1,2和3这样的数字,我想把它们变成字符串,"01","02"和"03".我怎样才能做到这一点?

Kel*_*sey 28

string.Format("{0:00}", yourInt);

yourInt.ToString("00");
Run Code Online (Sandbox Code Playgroud)

两者都生产01,02等......


Tus*_*har 11

string.Format("{0:00}",1); //Prints 01
string.Format("{0:00}",2); //Prints 02
Run Code Online (Sandbox Code Playgroud)


小智 8

使用新的 C#(我的意思是版本 6.0),您只需使用字符串插值即可实现相同的效果

int n = 1;
Console.WriteLine($"{n:D2}");
Run Code Online (Sandbox Code Playgroud)