Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I align text in columns using Console.WriteLine?

I have a sort of column display, but the end two column's seem to not be aligning correctly. This is the code I have at the moment:

Console.WriteLine("Customer name    "      + "sales          "      + "fee to be paid    "      + "70% value       "      + "30% value"); for (int DisplayPos = 0; DisplayPos < LineNum; DisplayPos = DisplayPos + 1) {     seventy_percent_value = ((fee_payable[DisplayPos] / 10.0) * 7);     thirty_percent_value = ((fee_payable[DisplayPos] / 10.0) * 3);               Console.WriteLine(customer[DisplayPos] + "         "          + sales_figures[DisplayPos] + "               "          + fee_payable[DisplayPos] + "           "          + seventy_percent_value + "           "          + thirty_percent_value); } 
like image 844
Stephen Smith Avatar asked Dec 15 '10 10:12

Stephen Smith


People also ask

How do I align text in console?

Align String with Spaces [C#] The example formats text to table and writes it to console output. To align string to the right or to the left use static method String. Format. To align string to the left (spaces on the right) use formatting patern with comma (,) followed by a negative number of characters: String.

What is use of console WriteLine () method?

WriteLine(String, Object, Object) Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information.


2 Answers

Try this

Console.WriteLine("{0,10}{1,10}{2,10}{3,10}{4,10}",   customer[DisplayPos],   sales_figures[DisplayPos],   fee_payable[DisplayPos],    seventy_percent_value,   thirty_percent_value); 

where the first number inside the curly brackets is the index and the second is the alignment. The sign of the second number indicates if the string should be left or right aligned. Use negative numbers for left alignment.

Or look at http://msdn.microsoft.com/en-us/library/aa331875(v=vs.71).aspx

like image 119
royas Avatar answered Sep 21 '22 15:09

royas


Just to add to roya's answer. In c# 6.0 you can now use string interpolation:

Console.WriteLine($"{customer[DisplayPos],10}" +                   $"{salesFigures[DisplayPos],10}" +                   $"{feePayable[DisplayPos],10}" +                   $"{seventyPercentValue,10}" +                   $"{thirtyPercentValue,10}"); 

This can actually be one line without all the extra dollars, I just think it makes it a bit easier to read like this.

And you could also use a static import on System.Console, allowing you to do this:

using static System.Console;  WriteLine(/* write stuff */); 
like image 39
Daniel Hakimi Avatar answered Sep 21 '22 15:09

Daniel Hakimi