简体   繁体   中英

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}", 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.

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<

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM