3

How do I create a “0000001”-type number format in C#?

    0000001
    0000002
    0000003
    .
    .
    .
    .
    .
    0000010
    0000011
    .
    .
    .
    0000100
    0000101

How could I generate this type of number format in C#/.NET?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Coderz
  • 245
  • 6
  • 20
  • Generate it WHERE? Ever heard of string.Format - look up the format strings, there is one for formatting numbers that does put leading zeroes as needed. – TomTom Feb 23 '14 at 07:14
  • Either change `0000003` example or add clarification, as you are confusing fellow stackoverflowers with what you want. ( I think you want binary padded to 8 digits ) – vittore Feb 23 '14 at 07:19
  • possible duplicate of [How can I format a number into a string with leading zeros?](http://stackoverflow.com/questions/5418324/how-can-i-format-a-number-into-a-string-with-leading-zeros) – myermian Feb 23 '14 at 07:22

5 Answers5

3

You can use the Convert.ToString method and pass it to the base parameter. Like 2, 8, 16, if that's what you mean.

int number = 124;
string binary = Convert.ToString(number, 2); // Output: 1111100
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

Numbers/values don't have a format unless you decide to get a string representation of the value itself.

To get string representation of int value you can use ToString with format specified:

var value = 0;
var valueStringRepresentation = value.ToString("0000000");

"0" in ToString() call is a zero placeholder and means:

Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

from Custom Numeric Format Strings

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
2
String.Format(CultureInfo.InvariantCulture, "{0:0000000}", number);
myermian
  • 31,823
  • 24
  • 123
  • 215
2
int i = 1;
Console.WriteLine(i.ToString("D8"));
w.b
  • 11,026
  • 5
  • 30
  • 49
-1

You could use PadLeft in C#, like below:

string s = "1";
Console.WriteLine(s.PadLeft(7, '0'));

Please visit String.PadLeft Method (MSDN) for details.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
linpingta
  • 2,324
  • 2
  • 18
  • 36