6

I am trying to format some c# output so that a number always has 2 digits for instance if int = 0 i would like Console.WriteLine(int); to produce 00.

3 Answers 3

9

Take a look at http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

This should do what you want:

        int num = 10;

        Console.WriteLine(num.ToString("0#"));

        Console.ReadLine();

The string that is passed to the ToString method "0#" has the following meaning:

0 - 0 place holder, this will be replaced with relevant digit if one exists
# - digit place holder.

So if num is 0, 00 will be written to the console but if num is 10, 10 will be written to the console.

Sign up to request clarification or add additional context in comments.

Comments

5

for example

for (int i = 0; i < 100; i++)
{
       Console.WriteLine("{0:00}", i);    
}

Comments

4

Take a look at this page, esp. the "Custom number formatting" section.

To show a number as two digits only you'd do something like this:

int x = 2;
string output = string.Format("{0:00}", x);
Console.WriteLine(output);

1 Comment

+1 for using string.Format instead of Console.WriteLine (more general solution)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.