Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
680 views
in Technique[技术] by (71.8m points)

c# - Number increment from string value

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...