1

I'm trying to add commas to the following line of code:

Console.WriteLine(String.Format("{0, 8} {1,8} {2,8}", number, square, cube));

How does one use alignment formatting in conjunction with adding commas?

0

3 Answers 3

3

It's this way {0,8:N2}

N2 will format with comma based on locale.

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

Comments

0

Output sample could be useful... This: String.Format("{0, 8}, {1,8}, {2,8}", number, square, cube)); ?

Or you are looking for Number formatting that has thousands separator? Than you need to specify desired CultureInfo as first argument of the String.Format.

Comments

0

Try adding in the commas to the numbers before performing the alignment formatting (modifying based on your locale/culture, if necessary):

Console.WriteLine(
        String.Format("{0, 8} {1,8} {2,8}", 
                      number.ToString("#,0"), 
                      square.ToString("#,0"), 
                      cube.ToString("#,0")
        )
);

And as Jeff points out in his comment below, you can also accomplish this by including the comma formats inline with the alignment formatting (the first part of each format block gives the alignment, the second part formats the string):

Console.WriteLine("{0,8:#,0} {1,8:#,0} {2,8:#,0}", number, square, cube);

1 Comment

You don't need to explicitly call ToString() here, just tack on the format to in the parameters. Console.WriteLine("{0,8:0,0} {1,8:0,0} {2,8:0,0}", number, square, cube);

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.