Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number increment from string value

Tags:

c#

I my application due to some reason I have two numbers in 5 digits.

The following code give you brief idea.

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. i.e 00001 to 00002

This can be done easily by convert the value of s to int and increment it by 1 but after all that I have to also store the incremented value of s in 5 digit so it will be "00002".

This think give me a pain...

like image 656
Sagar Upadhyay Avatar asked Dec 02 '22 20:12

Sagar Upadhyay


2 Answers

use

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

to get atleast 5 digits.

The "D" (or decimal) format specifier

If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no precision specifier is specified, the default is the minimum value required to represent the integer without leading zeros.

like image 180
Habib Avatar answered Dec 23 '22 18:12

Habib


This seems to work for me.

string s = "00001";
int i = Int32.Parse(s);
i++;
s = i.ToString("D" + s.Length);
like image 30
Smetad Anarkist Avatar answered Dec 23 '22 19:12

Smetad Anarkist