dijam
dijam

Reputation: 668

C# formatting text (right align)

I am a beginner learning C#, I am making a mock shopping list receipt program to manage your shopping. I generate .txt receipt however having problem with right align string here is my code;

public static void GenerateNewReciept(Customer customer)
{
    List<ShoppingItems> customerPurchaedItems;
    try
    {
        sw = File.AppendText("receipt.txt");

        //Customer object
        Customer customers = customer;
        //List of all items in list
        List<ShoppingList> customerItems = customer.CustomerShoppingList;
        DateTime todayDandT = DateTime.Now;

        //Making reciept layout
        sw.WriteLine("Date Generated: " + todayDandT.ToString("g", CultureInfo.CreateSpecificCulture("en-us")));
        sw.WriteLine("Customer: " + customer.FName + " " + customer.SName1);

        for (int i = 0; i < customerItems.Count; i++)
        {
            customerPurchaedItems = customerItems[i].ShoppingItems;
            foreach (ShoppingItems item in customerPurchaedItems)
            {
                sw.WriteLine(String.Format("{0,0} {1,25:C2}", item.ItemName, item.Price));  
            }
        }

        sw.WriteLine("Total {0,25:C2}", customerItems[0].computeTotalCost());
        sw.Close();
    }
    catch (FileNotFoundException)
    {
        Console.WriteLine("FILE NOT FOUND!");
    }
}

sw.WriteLine(String.Format("{0,0} {1,25:C2}", item.ItemName, item.Price)); sw.WriteLine("Total {0,25:C2}", - I want the prices of the items to be right aligned however some items have larger names, meaning when 25 spacing is applied they will be out of place.This is the same with total.

Upvotes: 5

Views: 12568

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109547

There actually is a way to do this with built-in formatting:

using System;

namespace Demo
{
    static class Program
    {
        public static void Main()
        {
            printFormatted("Short", 12.34);
            printFormatted("Medium", 1.34);
            printFormatted("The Longest", 1234.34);
        }

        static void printFormatted(string description, double cost)
        {
            string result = format(description, cost);
            Console.WriteLine(">" + result + "<");
        }

        static string format(string description, double cost)
        {
            return string.Format("{0,15} {1,9:C2}", description, cost);
        }
    }
}

This prints:

>          Short    £12.34<
>         Medium     £1.34<
>    The Longest £1,234.34<

Upvotes: 5

Related Questions