格式化C#输出
我正在尝试格式化一些c#输出,以便一个数字总是有两位数字,例如,如果格式化C#输出,c#,formatting,C#,Formatting,我正在尝试格式化一些c#输出,以便一个数字总是有两位数字,例如,如果int=0我想要Console.WriteLine(int)生成00。请查看 这应该满足您的要求: int num = 10; Console.WriteLine(num.ToString("0#")); Console.ReadLine(); 传递给ToString方法“0#”的字符串具有以下含义: 0 - 0 place holder, this will be repl
int=0
我想要Console.WriteLine(int)代码>生成00。请查看
这应该满足您的要求:
int num = 10;
Console.WriteLine(num.ToString("0#"));
Console.ReadLine();
传递给ToString方法“0#”的字符串具有以下含义:
0 - 0 place holder, this will be replaced with relevant digit if one exists
# - digit place holder.
因此,如果num为0,00将写入控制台,但如果num为10,10将写入控制台 查看
示例
for (int i = 0; i < 100; i++)
{
Console.WriteLine("{0:00}", i);
}
for(int i=0;i<100;i++)
{
Console.WriteLine(“{0:00}”,i);
}
看一看,尤其是“自定义数字格式”部分
要仅将数字显示为两位数,请执行以下操作:
int x = 2;
string output = string.Format("{0:00}", x);
Console.WriteLine(output);
+1用于使用string.Format代替Console.WriteLine(更通用的解决方案)