Friday, May 28, 2021

C# String Format Method Examples

String.Format method uses the composite formatting feature to include zero-based indexed placeholders, called format items, in a composite format string. At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is null, the format item is replaced with String.Empty
A format item has this syntax:{index[,alignment][:formatString]}
Brackets denote optional elements. The opening and closing braces are required.

Index: The zero-based index of the argument whose string representation is to be included at this position in the string. If this argument is null, an empty string will be included at this position in the string.
Width and alignment: A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer).

Types of formatString
Standard numeric format strings are used to format common numeric types. A standard numeric format string takes the form [format specifier][precision specifier], where:

Standard Numeric Format specifier is a single alphabetic character in lower or upper case that is used to format a number into comma-separated, currency or percentage format etc. Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string.

The  single alphabetic character can be c for currency, d for decimal, e for exponential, f for fixed-point, g for general, n for number, p for percentage, x for hexadecimal format. Note the datatype of number be considered before applying the format on a number. The character can be in lower or upper case.

Precision specifier is an optional integer that affects the number of digits in the resulting string.
Example1
using System;
namespace ConsoleCompositeFormat
{// String.Format syntax => {index[,alignment][:formatString]}
    class Program
    {
        static void Main(string[] args)
        {
            Decimal pricePerOunce = 17.36m;
            String s = String.Format("The current price is {0} per ounce.",
                                     pricePerOunce);
            Console.WriteLine(s);
            // Result: The current price is 17.36 per ounce.
            String s2 = String.Format("The current price is {0:C2} per ounce.",
                                     pricePerOunce);
            Console.WriteLine(s2);
            // Result if current culture is en-US:
            //      The current price is $17.36 per ounce.
            decimal temp = 20.4m;
            string s3 = String.Format("The temperature is {0}°C.", temp);
            Console.WriteLine(s3);
            // Displays 'The temperature is 20.4°C.'
            string s4 = String.Format("At {0}, the temperature is {1}°C.",
                         DateTime.Now, 20.4);
            Console.WriteLine(s4);
            // Output similar to: 'At 4/10/2015 9:29:41 AM, the temperature is 20.4°C.'
            string s5 = String.Format("It is now {0:d} at {0:t}", DateTime.Now);
            Console.WriteLine(s5);
            // Output similar to: 'It is now 4/10/2015 at 10:04 AM'
            //control spacing:-->
            int[] years = { 2013, 2014, 2015 };
            int[] population = { 1025632, 1105967, 1148203 };
            var sb = new System.Text.StringBuilder();
            //{0,6}=> insert 6 characters for 0-index text and right-align the text
            //{0,15}=> insert 15 characters for 1-index text and right-align the text
            sb.Append(String.Format("{0,6} {1,15}\n\n", "Year", "Population"));
            for (int index = 0; index < years.Length; index++)
                sb.Append(String.Format("{0,6} {1,15:N0}\n", years[index], population[index]));

            Console.WriteLine(sb);

            // Result:
            //      Year      Population
            //
            //      2013       1,025,632
            //      2014       1,105,967
            //      2015       1,148,203

            //Control alignment
            //{0,-10}=> insert 10 characters for 0-index text and left-align the text
            //{1,-10}=> insert 10 characters for 1-index text and left-align the text
            String s6 = String.Format("{0,-10} {1,-10}\n\n", "Year", "Population");
            for (int index = 0; index < years.Length; index++)
                s6 += String.Format("{0,-10} {1,-10:N0}\n",
                                   years[index], population[index]);
            Console.WriteLine($"\n{s6}");
            // Result:
            //    Year       Population
            //
            //    2013       1,025,632
            //    2014       1,105,967
            //    2015       1,148,203
            Console.ReadKey();
        }
    }
}



The custom numeric format specifier can be more than one characters. The zero, hash, dot, comma, percentage, semi-colon etc. symbols are used for custom numeric format. Examples are 00000, 0.00, #.#, etc.

Number

Display  Format

Format Rule Applied

123

00123

00000

1.2

1.20

0.00

1.2

01.20

00.00

1.2

1.2

#.##

123456

[12-34-56]

[##-##-##]

1234567890

(123) 456-7890

(###) ###-####

.56

0.6

0.0

1234567890

1,234,567,890

0,0

1234567890

1,234,567,890

#,#

.086

8.6%

#0.##%

 -1234

 (1234)

 ##;(##)


The  single alphabetic character is used for Standard date and time formatting.

The character is case-sensitive. It means that the lower and upper case character will format differently.

The d for short date pattern, D for long date pattern.

The f for short time full date pattern, F for long time full date pattern.

The t for short time pattern, T for long time pattern.

using System;

using System.Globalization;

namespace ConsoleFormat1

{

    class Program

    {

        static void Main(string[] args)

        {

            // Display using current (en-us) culture's short date format

            DateTime thisDate = new DateTime(2008, 3, 15);

            Console.WriteLine(thisDate.ToString("d"));// Displays 3/15/2008

            // Display using pt-BR culture's short date format

            CultureInfo culture = new CultureInfo("pt-BR");

            Console.WriteLine(thisDate.ToString("d", culture)); // Displays 15/3/2008

            // Display using dateformat information from hr-HR culture

            DateTimeFormatInfo fmt = (new CultureInfo("hr-HR")).DateTimeFormat;

            Console.WriteLine(thisDate.ToString("d", fmt)); // Displays 15.3.2008

 

            DateTime date1 = new DateTime(2008, 4, 10);

            Console.WriteLine(date1.ToString("D",

                              CultureInfo.CreateSpecificCulture("en-US")));

            // Displays Thursday, April 10, 2008

            Console.WriteLine(date1.ToString("D",

                              CultureInfo.CreateSpecificCulture("pt-BR")));

            // Displays quinta-feira, 10 de abril de 2008

            Console.WriteLine(date1.ToString("D",

                              CultureInfo.CreateSpecificCulture("es-MX")));

            // Displays jueves, 10 de abril de 2008

 

            Console.WriteLine(date1.ToString("f",

                              CultureInfo.CreateSpecificCulture("en-US")));

            // Displays Thursday, April 10, 2008 6:30 AM

            Console.WriteLine(date1.ToString("f",

                              CultureInfo.CreateSpecificCulture("fr-FR")));

            // Displays jeudi 10 avril 2008 06:30

 

            Console.WriteLine(date1.ToString("F",

                              CultureInfo.CreateSpecificCulture("en-US")));

            // Displays Thursday, April 10, 2008 6:30:00 AM

            Console.WriteLine(date1.ToString("F",

                              CultureInfo.CreateSpecificCulture("fr-FR")));

            // Displays jeudi 10 avril 2008 06:30:00

 

            Console.WriteLine(date1.ToString("g",

                              DateTimeFormatInfo.InvariantInfo));

            // Displays 04/10/2008 06:30

            Console.WriteLine(date1.ToString("g",

                              CultureInfo.CreateSpecificCulture("en-us")));

            // Displays 4/10/2008 6:30 AM

            Console.WriteLine(date1.ToString("g",

                              CultureInfo.CreateSpecificCulture("fr-BE")));

            // Displays 10/04/2008 6:30

 

            Console.WriteLine(date1.ToString("U",

                              CultureInfo.CreateSpecificCulture("en-US")));

            // Displays Thursday, April 10, 2008 1:30:00 PM

            Console.WriteLine(date1.ToString("U",

                              CultureInfo.CreateSpecificCulture("sv-FI")));

            // Displays den 10 april 2008 13:30:00

 

            Console.WriteLine(date1.ToString("t",

                              CultureInfo.CreateSpecificCulture("en-us")));

            // Displays 6:30 AM

            Console.WriteLine(date1.ToString("t",

                              CultureInfo.CreateSpecificCulture("es-ES")));

            // Displays 6:30

 

            Console.WriteLine(date1.ToString("T",

                              CultureInfo.CreateSpecificCulture("en-us")));

            // Displays 6:30:00 AM

            Console.WriteLine(date1.ToString("T",

                              CultureInfo.CreateSpecificCulture("es-ES")));

            // Displays 6:30:00

 

            Console.WriteLine(date1.ToString("Y",

                              CultureInfo.CreateSpecificCulture("en-US")));

            // Displays April, 2008

            Console.WriteLine(date1.ToString("y",

                              CultureInfo.CreateSpecificCulture("af-ZA")));

            // Displays April 2008

 

            Console.ReadKey();

        }

    }

}

 


No comments:

Post a Comment

Hot Topics