Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center align arguments in a format string

Tags:

c#

I have a string (like below), and I want each of the argument to be center aligned.

There is an option for left align that is ("+") and right align that is ("-") but I want to center align.

basketItemPrice = string.Format("\n\n{0, -5}{1, -14:0.00}{2, -18:0.00}{3,-14:0.00}{4,6}{5,-12:0.00}", item.Quantity, item.OrderItemPrice, item.MiscellaniousCharges, item.DiscountAmountTotal, "=", item.UpdateItemAmount(Program.currOrder.OrderType));
like image 276
NoviceToDotNet Avatar asked Sep 02 '13 12:09

NoviceToDotNet


People also ask

How do I center a string format?

You can now use StringUtils. center(String s, int size) in String. format .

How do I center a string format in Python?

Python String center() MethodThe center() method will center align the string, using a specified character (space is default) as the fill character.

How do I center a string in C#?

double theObject = Math. PI; string test = string. Format("Now '{0:F4}' is used.", theObject. Center(10));

How do you right align a string in Python?

You can use the :> , :< or :^ option in the f-format to left align, right align or center align the text that you want to format. We can use the fortmat() string function in python to output the desired text in the order we want.


2 Answers

Unfortunately, this is not supported natively by String.Format. You will have to pad your string yourself:

static string centeredString(string s, int width)
{
    if (s.Length >= width)
    {
        return s;
    }

    int leftPadding = (width - s.Length) / 2;
    int rightPadding = width - s.Length - leftPadding;

    return new string(' ', leftPadding) + s + new string(' ', rightPadding);
}

Usage example:

Console.WriteLine(string.Format("|{0}|", centeredString("Hello", 10)));
Console.WriteLine(string.Format("|{0}|", centeredString("World!", 10)));
like image 130
Heinzi Avatar answered Oct 18 '22 15:10

Heinzi


I tried to make an extension method which still preserves the IFormattable support. It uses a nested class which remembers the raw value and the desired width. Then when format string is provided, it is used, if possible.

It looks like this:

public static class MyExtensions
{
    public static IFormattable Center<T>(this T self, int width)
    {
        return new CenterHelper<T>(self, width);
    }

    class CenterHelper<T> : IFormattable
    {
        readonly T value;
        readonly int width;

        internal CenterHelper(T value, int width)
        {
            this.value = value;
            this.width = width;
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            string basicString;
            var formattable = value as IFormattable;
            if (formattable != null)
                basicString = formattable.ToString(format, formatProvider) ?? "";
            else if (value != null)
                basicString = value.ToString() ?? "";
            else
                basicString = "";

            int numberOfMissingSpaces = width - basicString.Length;
            if (numberOfMissingSpaces <= 0)
                return basicString;

            return basicString.PadLeft(width - numberOfMissingSpaces / 2).PadRight(width);
        }
        public override string ToString()
        {
            return ToString(null, null);
        }
    }
}

Note: You have not indicated if you want the one "extra" space character put to the left or to the right in cases where an odd number of space characters needs to be appended.

This test seems to indicate it works:

double theObject = Math.PI;
string test = string.Format("Now '{0:F4}' is used.", theObject.Center(10));

Of course, format string F4 with a double means "round to 4 decimal places after the decimal point".

like image 33
Jeppe Stig Nielsen Avatar answered Oct 18 '22 14:10

Jeppe Stig Nielsen