4

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Sham
  • 830
  • 9
  • 27
  • 3
    `1234 == 01234` for integers, `0` will be ignored. For displaying purpose you can use string format to pad a leading `0` – Habib Nov 21 '12 at 07:35
  • Possible duplicate [How can I format a number into a string with leading zeros?](http://stackoverflow.com/questions/5418324/c-sharp-how-can-i-format-a-number-into-a-string-with-leading-zeros) – horgh Nov 21 '12 at 07:53

5 Answers5

8

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"
prime23
  • 3,362
  • 2
  • 36
  • 52
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • We can do that using PadLeft, my question is can we convert to int when a string has prefixed with zero. It seems to be not possible by looking at the comments below. – Sham Nov 21 '12 at 08:42
  • @sham leading zeros make no sense for an integer -- can't you generate your range of numbers, then pad after converting back to a string? – McGarnagle Nov 21 '12 at 08:45
  • Thanks for your input. I guess that would be the only option left out. – Sham Nov 21 '12 at 08:55
6
 int num = 1234;
 Console.WriteLine(num.ToString("D5"));  // "01234"
Simon Hughes
  • 3,534
  • 3
  • 24
  • 45
0

No with int.

You have to use string to concatenate the parsed number and the 0

Gianni B.
  • 2,691
  • 18
  • 31
0
int num = 1234;
Console.WriteLine($"{num:d5}");
-1

I think you can use string.Format

    int num = 1234;
    Console.WriteLine(string.Format("0{0}", num));
leon_ALiang
  • 79
  • 1
  • 5