Question

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?

Was it helpful?

Solution 2

String.Format(CultureInfo.InvariantCulture, "{0:0000000}", number);

OTHER TIPS

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

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

int i = 1;
Console.WriteLine(i.ToString("D8"));

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top