1

I'm working with numbers stored in a string in C#.

I have some number such as 22408061. I would like to add dynamic 0 characters to have 12 characters giving 000022408061.

As another example, given 12322408061, it needs to be 012322408061.

Conspicuous Compiler
  • 6,403
  • 1
  • 40
  • 52
Ola
  • 1,188
  • 5
  • 16
  • 35
  • 7
    Possible duplicate of [everything](https://www.google.co.uk/search?q=c%23+pad+with+zeros). (Note to self: get 100+k reputation by answering obvious duplicate questions.) – Rawling Mar 14 '14 at 14:45
  • 2
    Please consider that the asker propably did not know about the term "padding" to find the correct answer. At least for me as non-native speaker this wasn't clear when I didn't know yet about padding. – Marwie Mar 14 '14 at 14:49
  • 1
    [Extra zeroes](https://www.google.co.uk/search?q=c%23+extra+zeros)? – Rawling Mar 14 '14 at 14:51
  • Do you have number to begin with or is it a string containing number ? – Habib Mar 14 '14 at 15:06

4 Answers4

6

You are looking for PadLeft method.

var str = "22408061".PadLeft(12, '0');
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

This is a string in c#.

You can use PadLeft:

string text = "22408061";
text = text.PadLeft(12, '0'); // 000022408061
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

http://msdn.microsoft.com/en-us/library/92h5dc07(v=vs.110).aspx

Console.WriteLine(str.PadLeft(12, pad));

Stachu
  • 5,677
  • 3
  • 30
  • 34
0

Logic is :

  1. count the number of length, say for eg in 22408061 you will get 8 length

  2. subtract 12 - 8 = 4 i.e. total value - length

  3. which ever number you get, add that many zeros before the number.

Aditi
  • 509
  • 4
  • 20