Friday, May 28, 2021

C# String Format Method Examples

Main Points

  • String.Format built-in method returns a formatted string.
  • There are 13 overloaded versions of this method.
  • It takes string as first argument (called format string) for formatting the remaining arguments.
  • The remaining arguments can be of any type data value.
  • Syntax, version2: String.Format(string format, params object[]  args)
  • The first argument is called format string.
  • The remaining arguments are called objects, which are formatted inside format string using format item.
  • The formatting rules for these objects are specified in format string.
  • Each object is assigned a zero-based index, starting from 0 similar to array elements.
  • The format item is placeholder denoted by {} inside format string.
  • The 1st format item is denoted by {0}. The 2nd format item is denoted by {1} and so on.
  • The index is placed inside the placeholder e.g. {0}. The index value denotes which object will be formatted. For example, 0 is for first object, 1 for second object and so on.
  • Same object can be formatted more than once. E.g., 
    • String.Format(“{0:C} {0:D}”, 123);
    • String.Format("{ 0:C}{ 0:D}", 123);
  • Numbers can be formatted using special symbols e.g. C,D,E,F,G. Where C → Currency, D → Decimal, E→ Exponent,

EXAMPLE. Number Formatting

Console.WriteLine("{0}, {1}, {2}, {3},{4}", 100, 200, 300, 400, 500);
Console.WriteLine("{0:c}, {1:d}, {2:e}, {3:f},{4:g}", 100, 200, 300, 400, 500);
Console.WriteLine("{0:C}, {1:D}, {2:E}, {3:F},{4:G}", 100, 200, 300, 400, 500);

The formatting allows left or right alignment.

EXAMPLE. Number Formatting, currency format

Console.WriteLine(String.Format("{0}", 123));
Console.WriteLine(String.Format("{0:C}", 123));
Console.WriteLine(String.Format("{0:C1}", 123));
Console.WriteLine(String.Format("{0:C2}", 123));
Console.WriteLine(String.Format("{0:C3}", 123));
/*
123
$123.00
$123.0
$123.00
$123.000
 */

Number or Text Formatting, left alignment

Console.WriteLine(String.Format("{0  }", 123));
Console.WriteLine(String.Format("{0,10}", 123));
Console.WriteLine(String.Format("{0,9}", 123));
Console.WriteLine(String.Format("{0,8}", 123));
Console.WriteLine(String.Format("{0,7}", 123));
/*
123
       123
      123
     123
    123
 */


String.Format method in Details

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 Format String

Standard Numeric Format Strings

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

What is Format Specifier
  • 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.
  • 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.
  • Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a Custom Numeric Format string.
  • Note the datatype of number (e.g. decimal, integer, double etc.) be considered before applying the format on a number. The format character can be in lower or upper case.
What is Precision specifier
  • Precision specifier is an optional integer that affects the number of digits in the resulting string.
Custom Numeric Format Specifier
  • 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.

Example
using System.Globalization;
namespace FormatDateDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime thisDate = new DateTime(2008, 3, 15);
            Console.WriteLine(thisDate.ToString("d"));// Displays 3/15/2008
            CultureInfo culture = new CultureInfo("pt-BR");
            Console.WriteLine(thisDate.ToString("d", culture)); // Displays 15/3/2008
            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")));
            Console.WriteLine(date1.ToString("F",
                              CultureInfo.CreateSpecificCulture("fr-FR")));
            // Displays jeudi 10 avril 2008 06:30:00
            Console.WriteLine(date1.ToString("g",
                              DateTimeFormatInfo.InvariantInfo));
            Console.WriteLine(date1.ToString("U",
                              CultureInfo.CreateSpecificCulture("en-US")));
            Console.WriteLine(date1.ToString("t",
                              CultureInfo.CreateSpecificCulture("en-us")));
            Console.ReadKey();
        }
    }
}
/*
3/15/2008
15/03/2008
15. 03. 2008.
Thursday, April 10, 2008
jeudi 10 avril 2008 00:00:00
04/10/2008 00:00
Wednesday, April 9, 2008 6:30:00 PM
12:00 AM
 
 */

 


No comments:

Post a Comment

Hot Topics