在c#中,我有一个整数值,需要转换为字符串,但它需要在前面加零:

例如:

int i = 1;

当我把它转换成字符串时,它需要变成0001

我需要知道c#中的语法。


当前回答

int p = 3; // fixed length padding
int n = 55; // number to test

string t = n.ToString("D" + p); // magic     

Console.WriteLine("Hello, world! >> {0}", t);

// outputs: 
// Hello, world! >> 055

其他回答

c# 6.0风格的字符串插值

int i = 1;
var str1 = $"{i:D4}";
var str2 = $"{i:0000}";

你可以使用:

int x = 1;
x.ToString("0000");
string hello = "Hello C# Corner.";

string helloHash = hello.PadLeft(5, '#');  

Console.WriteLine(helloHash); 

输出:

#####Hello C# Corner.

填充int i以匹配int x的字符串长度,当两者都可以为负数时:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')
i.ToString("0000");