C# - increment number and keep zeros in front

拥有回忆 提交于 2019-12-03 10:53:39
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 answer for a formatting option that I can also never remember.

Try using

int myNumber = ...;
string output = myNumber.ToString("D40");

Of course, the int can never grow so huge as to fill out all those digit places (the greatest int having only 10 digits).

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:

// 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');

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!