Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to set a fix field width using string interpolation? [duplicate]

Tags:

c#

I am new to c# and in this case, I want to align text columns in a text block. So basically I am trying to print a receipt and on the receipt, it should look like this.

For example:

1 Dinner Set          $15.00
1 Hamburger Combo     $10.00

Basically, I want to align my text column for the receipt. Since the food item name length varies from the different food item. For instance "Dinner Set" and "Hamburger Combo" have different lengths. Therefore, whenever I use the code below it would come up like this

1 Diner Set          $15.00
1 Hamburger Combo       $10.00

Here is the code:

    foreach (OrderItem ot in orderItemList)
    {
      x += $"\n{ot.Quantity} {ot.Item.Name}\t\t 
      ${ot.GetItemTotalAmnt().ToString("0.00")}\n";
    }

Since I don't hardcode each line is there a way to set a fixed width on {ot.Item.Name}?

like image 341
jmsandiegoo Avatar asked Mar 07 '23 01:03

jmsandiegoo


2 Answers

As long as you're using a fixed-width font, use something like this:

string.Format("{0,-20}", ot.Item.Name)

The value after the comma says to use that many character spaces in the resulting string. If you use the following (notice I removed the minus sign):

string.Format("{0,20}", ot.Item.Name)

Then the text will be right-aligned within those spaces.

like image 56
Jonathan Wood Avatar answered Mar 30 '23 01:03

Jonathan Wood


You can specify the field width and format specifiers the same way with string interpolation as you can with String.Format().

x += $"\n{ot.Quantity} {ot.Item.Name,-20} ${ot.GetItemTotalAmnt():C}\n";

And if you don't want to hardcode 20, just use the maximum Item.Name as the field width.

var maxLength = orderItemList.Max(ot => ot.Item.Name.Length) 
like image 21
npearson Avatar answered Mar 30 '23 01:03

npearson