Reputation: 840
I have a situation where I need to prefix a zero to an integer. Initially I have string which has 12 chars, first 7 are alphabets and 5 are numeric values. The generated string some times have a zero at starting position of numeric values. for example ABCDEF*0*1234, and my scenario is to generate a range of strings from the generated string. Suppose I want to generate a range (assume 3 in number), so it would be ABCDEF01235, ABCDEF01236, ABCDEF01237.
When I try to convert a string which has a 0 (as shown above) to int, it returns only 1234. Is there any way to do this, without truncating zero?
Upvotes: 5
Views: 9973
Reputation: 102793
You can use PadLeft
to expand a given string to a given total length:
int num = 1234;
Console.WriteLine(num.ToString().PadLeft(5, '0')); // "01234"
Upvotes: 9
Reputation: 3574
int num = 1234;
Console.WriteLine(num.ToString("D5")); // "01234"
Upvotes: 7
Reputation: 79
I think you can use string.Format
int num = 1234;
Console.WriteLine(string.Format("0{0}", num));
Upvotes: -1
Reputation: 2731
No with int
.
You have to use string
to concatenate the parsed number and the 0
Upvotes: 0