C# convert int to string with padding zeros?

2018-12-31 09:13发布

In C# I have an integer value which need to be convereted to string but it needs to add zeros before:

For Example:

int i = 1;

When I convert it to string it needs to become 0001

I need to know the syntax in C#.

10条回答
裙下三千臣
2楼-- · 2018-12-31 09:38
i.ToString("D4");

See MSDN on format specifiers.

查看更多
路过你的时光
3楼-- · 2018-12-31 09:38

Here I want to pad my number with 4 digit. For instance, if it is 1 then it should show as 0001, if it 11 it should show as 0011.

Below is the code that accomplishes this:

reciptno=1; // Pass only integer.

string formatted = string.Format("{0:0000}", reciptno);

TxtRecNo.Text = formatted; // Output=0001

I implemented this code to generate money receipt number for a PDF file.

查看更多
ら面具成の殇う
4楼-- · 2018-12-31 09:39
i.ToString("0000");
查看更多
不再属于我。
5楼-- · 2018-12-31 09:40

Simply

int i=123;
string paddedI = i.ToString("D4");
查看更多
余欢
6楼-- · 2018-12-31 09:43

To pad int i to match the string length of int x, when both can be negative:

i.ToString().PadLeft((int)Math.Log10(Math.Abs(x < 0 ? x * 10 : x)) + 1, '0')
查看更多
不流泪的眼
7楼-- · 2018-12-31 09:45

You can use:

int x = 1;
x.ToString("0000");
查看更多
登录 后发表回答