C#格式化文本(右对齐)

时间:2016-03-17 08:45:29

标签: c#

我是初学者学习C#,我正在制作一个模拟购物清单收据计划来管理您的购物。我生成.txt收据然而右边对齐字符串的问题在这里是我的代码;

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}", - 我希望项目的价格正确对齐,但有些项目的名称较大,这意味着当应用25个间距时,它们将不合适。这与总数相同。

1 个答案:

答案 0 :(得分:2)

实际上 是一种使用内置格式化的方法:

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);
        }
    }
}

打印:

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