简体   繁体   中英

How can i get the last number from a List including the zeros?

int lastpadnum = padnumbers.Count;
int nextpadnum = lastpadnum + 1;

If the last number in the List padnumbers is 191 then in lastpadnum the value will be 191 and in nextpadnum the value will be 192.

But if in the List padnumbers the last number is "0000000000191" Then in lastpadnum i will see only 191. But i want to get the whole number "0000000000191" and to get it as int.

Then i tried this:

int lastpadnum = Convert.ToInt32(padnumbers[padnumbers.Count - 1]);
int nextpadnum = lastpadnum + 1;

But still when the last number in the list is "0000000000191" i'm getting only the 191.

And in the end i want to calculate the next number but not sure how to do it.If for example the last number is 191 the next one will be 192. But if the last number is 00191 the next one should be 00192 and if the last number is "0000000000191" then the next one should be "0000000000192".

"0000000000191" is not an int. It is a string. A variable of type int does not contain the leading zeroes, ever, nor does it contain any formatting information, ever. When you print it out, it is converted to a string, either implicitly or explicitly; it is not possible to literally print an int because it is actually held in a binary format.

If you want leading zeroes, you need to convert to a string. If you want the leading zeroes from some original value that had leading zeroes, you need to preserve that value; converting to an int automatically eliminates all formatting information whatsoever.

That being said, if you have a variable that contains 191 and you want to display it as 0000000000191, you simply need to format as a string, eg

int someValue = 191;
int valueString = someValue.ToString("0000000000000");
Console.Writeline(valueString);

If you're trying to maintain a sequence in string format, you can convert to an int, increment, then convert back, like this:

string lastpadstring = padnumbers[padnumbers.Count - 1];
int lastpadnum = Convert.ToInt32(lastpadstring);
int nextpadnum = lastpadnum + 1;
string nextpadstring = nextpadnum.ToString(new String('0', lastpadstring.Length));

191 and 00191 are the same number. It seems like what you're trying to do is to take a string with a zero-padded number, add one to the number, and then produce a new zero-padded string with the same length. Take a look at the below code and see if it does what you want:

string lastpadnum = "0000000000191";
int desiredLength = lastpadnum.Length;
int nextnum = Convert.ToInt32(lastpadnum) + 1;
string nextpadnum = nextnum.ToString().PadLeft(desiredLength, '0');
Console.WriteLine(nextpadnum);

// Output:
// 0000000000192

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM