Increment a number from a string value

I am my application for some reason I have two numbers of 5 digits.

The following code gives you a brief description.

string s = "00001"; // Initially stored somewhere. //Operation start string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + s; //Operation end //Increment the value of s by 1. ie 00001 to 00002 

This can be done easily by converting the value of s to int and incrementing it by 1, but after all I have to keep the increment of s in a 5-digit value, so that it is "00002" .

That think, give me pain ...

+4
source share
5 answers

use

 string s = "00001"; int number = Convert.ToInt32(s); number += 1; string str = number.ToString("D5"); 

to get at least 5 digits.

D (or decimal) format specifier

If necessary, the number is filled with zeros to the left of it to get the number of digits indicated by the precision specifier. If there is no precision specifier, the default is the minimum value required to represent an integer without leading zeros.

+11
source

It seems to work for me.

 string s = "00001"; int i = Int32.Parse(s); i++; s = i.ToString("D" + s.Length); 
+5
source

So, I think you want to know how to convert int to 5 digit string .

You can do it:

 int i = 1; string s = i.ToString("D5"); //s = "00001" 

Many examples are presented here.

+1
source

Use String.Format() for this:

 string str = String.Format({0:#####}, s); 

Take a look here .

0
source

This works using the PadLeft function:

 int i = 1; // Initially stored somewhere. //Operation start string id = DateTime.Now.ToString("yy") + DateTime.Now.AddYears(-1).ToString("yy") + i.ToString().PadLeft(5, '0'); //Operation end 
0
source

Source: https://habr.com/ru/post/1469225/


All Articles