C# - 增加数字并在前面保留零
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10935020/
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
C# - increment number and keep zeros in front
提问by blizz
I need to make a 40 digit counter variable. It should begin as 0000000000000000000000000000000000000001
and increment to 0000000000000000000000000000000000000002
我需要制作一个 40 位的计数器变量。它应该开始0000000000000000000000000000000000000001
并增加到0000000000000000000000000000000000000002
When I use the intclass, it cuts off all the zeros. Problem is I need to increment the number and then convert it to a string, with the correct number of leading zeros. The total size should be 40 digits. So if I hit 50 for example, it should look like this:
当我使用这个int类时,它会切断所有的零。问题是我需要增加数字,然后将其转换为字符串,并带有正确数量的前导零。总大小应为 40 位数字。因此,例如,如果我达到 50,它应该如下所示:
0000000000000000000000000000000000000050
0000000000000000000000000000000000000050
How can I do that and retain the zeros?
我怎样才能做到这一点并保留零?
采纳答案by Anthony Pegram
Use the integer and format or pad the result when you convert to a string. Such as
转换为字符串时,使用整数和格式或填充结果。如
int i = 1;
string s = i.ToString().PadLeft(40, '0');
See Jeppe Stig Nielson's answerfor a formatting option that I can also never remember.
请参阅Jeppe Stig Nielson 的答案,了解我也永远不会记得的格式选项。
回答by Jeppe Stig Nielsen
Try using
尝试使用
int myNumber = ...;
string output = myNumber.ToString("D40");
Of course, the intcan never grow so huge as to fill out all those digit places (the greatest inthaving only 10 digits).
当然,int永远不会增长到填满所有这些数字位置(最大的int只有 10 位数字)。
回答by alfongad
Just convert your string to int, perform the addition or any other operations, then convert back to string with adequate number of leading 0's:
只需将您的字符串转换为 int,执行加法或任何其他操作,然后转换回具有足够数量的前导 0 的字符串:
// 39 zero's + "1"
string initValue = new String('0', 39) + "1";
// convert to int and add 1
int newValue = Int32.Parse(initValue) + 1;
// convert back to string with leading zero's
string newValueString = newValue.ToString().PadLeft(40, '0');
回答by Sapiens
I had to do something similar the other day, but I only needed two zeros. I ended up with
前几天我不得不做类似的事情,但我只需要两个零。我结束了
string str = String.Format("{0:00}", myInt);
Not sure if it's fool proof but try
不确定这是否是傻瓜证明,但请尝试
String.Format("{0:0000000000000000000000000000000000000000}", myInt)
回答by rio gunawan
You can use this too..
你也可以用这个..
int number = 1;
string tempNumber = $"{number:00}";
result:
结果:
01

