This page has been translated using an automatic translation service and the translation may not be very accurate.

Formattazione of stringhe in NET (English)

If you use this code and feel it is a useful tool, consider making a donation (through PayPal) to help support the project. You can donate as little or as much as you wish, any amount is greatly appreciated!

Italian page For the original Italian page, please click on the link: http://www.guru4.net/articoli/format-string/default.aspx

NET the Framework supplies one immense range of options for formattare stringhe, therefore to represent in exaustive way the main types (numerical, dates, currency, enumeratori, etc.)
In this article they will come evidanziati the various ones you form to you available, supplying for every case an exaustive example of I use, therefore to constitute one valid guide to hold always sottomano.

In particular they will come supplied indications on the identificatori of format for:

Format Item

Typically the formattazione of stringhe is one of the used characteristics more than a language. In NET we have various methods that take advantage of the composition of stringhe through the saying use placeholder (also format item) like as an example:

  • String.Format that gives back tightens it formattata

  • Console.WriteLine that extension tightens it formattata in the consul

  • TextWriter.WriteLine that writes tightens it formattata in one stream or rows

We as an example consider the overload of String.Format following:

public static string Format (string format, params Object[] args)

The directory of objects args represents with of values replacing to respects format item to you that they space out the fixed text in income format.

The segnaposto they come expressed in the shape:

{index[, alignment][:formatString ]}

where:

  • index it represents the numerical index (than part from zero) correspondent to the object in the directory of the args.

    Eventual elements of args you deprive of a correspondent segnaposto will not come considers you, while eventual segnaposto lacking in the correspondent an element in args it will raise one runtime exception

  • alignment it is an optional element of entire type with sign that indicates the turning out width of the formattato field. The turning out value will be aligned to the right of the field if alignment it is positive or on the left if alignment is negative.

    If the value of alignment is inferior to the length of it tightens formattata the parameter does not come considered.

  • formatString it is an optional parameter that specific the format for the rappresentazione of single format the item. The continuation of the article for the description of the values admitted for formatString is looked at in function of the type of object that is desired to represent.

    If formatString it comes omitted it will come used the general format ("G")

FAMOUS: the parentheses belt fasteners are interpreted like identificatori of placeholder; in order to represent apertuta of a parenthesis the belt fastener in the result of the formattazione it is necessary to insert two openings of parenthesis belt fasteners ({{) in the fixed text format; the management of escaping of the closing of the parentheses the belt fastener is analogous to that one for the opening of the same one (}} in order to represent })

The objects in args will come represent to you in format tighten like:

  1. if null as it tightens empty ("")

  2. if the type implements the ICustomFormatter interface by means of the call to the ICustomFormatter.Format method

  3. if the type implements the IFormattable interface by means of the call to the IFormattable.ToString method

  4. by means of the call to the ToString method of the object (Object.ToString)

Output of all the examples that follow are reported to the Italian international formulations: CultureInfo("it-IT")

DEMO 1

The following code:

string Name = "Matteo";
Console.WriteLine("I am '{0}'", Name);
Console.WriteLine("I am '{0,10}'", Name);
Console.WriteLine("I am '{0,-10}'", Name);

Produrra:

Am ' the Matteo'
Am '    the Matteo'
Am ' the Matteo    '

Formattazione of numerical types

The formattazione of a numerical type can be in shape standard (by means of the application of one style predefined for the specific numerical type with the possibility to define of the precision) or custom (by means of a format specified from the customer)

Stringhe of numerical format standard

The formattazione standard previews the declaration of the format in the Ann shape where To he is a single alphabetical character who specific the format (you see following table) and nn it is an entire one that specific the precision (optional)

Format Name Example Output
C (or c) Currency (currency) String.Format("{0:c}", 123456.789); String.Format("{0:c5}", 123456.789); String.Format("{0:c}", -123456.789); € 123.456,79 € 123.456,78900 -€ 123.456,79
D (or d) It decimates them String.Format("{0:d}", 123456); String.Format("{0:d10}", 123456); 123456 0000123456
And (or and) Scientific (esponenziale) String.Format("{0:e}", 123456.789); String.Format("{0:e10}", 123456.789); 1,234568e 005 12345678900 005
F (or f) To fixed virgola String.Format("{0:f}", 123456.789); String.Format("{0:f5}", 123456.789); 123456,79 123456,78900
G (or g) General String.Format("{0:g}", 123456.789); String.Format("{0}", 123456.789); 123456,79 123456,79

Predefinito (the two notations of example are equivalents).
The number comes converted in the more compact format between the scientific notation and that one to fixed virgola, to second of the type of number and the eventual presence of the identificatore of precision.

N (or n) Number String.Format("{0:n}", 123456.789); String.Format("{0:n5}", 123456.789); 123.456,79 123.456,78900

They come inserted separators of the migliaia between every group of three figures on the left of the separator decimates them.

P (or p) Percentage String.Format("{0:p}", 0.123456789); String.Format("{0:p}", 123456.789); String.Format("{0:p10}", 0.123456789); 12,35% 12.345.678,90% 12,3456789000%

The converted number comes multiplied for 100 so as to to be introduced like one percentage. The identificatore of precision indicates the number of positions decimates wished them.

R (or r) Reconversion String.Format("{0:r}", 123456.789); 123456,789

The identificatore of reconversion guarantees that a converted numerical value in one tightens comes brought back to the same numerical value. Although it is possible to add a identificatore of precision to the identificatore of reconversion format, such identificatore of precision comes however ignored. When this identificatore is used, in fact, the format of the reconversion has the precedence on the precision. This format is supported solo from the types to mobile virgola.

X (or x) Esadecimale (Hex) String.Format("{0:x}", 12); String.Format("{0:X}", 12); String.Format("{0:X}", 123456789); c C 75BCD15

The number comes converted in one tightens of esadecimali figures. I use of the capital letter and very small in the identificatore of format it indicates if they will come uses you characters capital letters or small letters for greater the esadecimali figures of 9.

Stringhe of personalized numerical format

If the identificatori of numerical format standard do not supply the type of wished formattazione, will be possible to use stringhe of personalized format. One tightens of format standard is constituted from a single alphabetical character, eventually followed from a sequence of figures that represents a value comprised between 0 and 99. All the others stringhe of format correspond to stringhe of personalized format.

Character of format Name Description
0 Segnaposto for zero If the value to formattare has a figure in the position in which in it tightens of format finds "0", such figure will come copied in tightens of turns out to you. The position of last "the 0" on the left before the separator decimates them and of last "the 0" to right after the separator it decimates determines them the interval of always present figures in tightens of turns out to you.
# Segnaposto for figures If the value to formattare has a figure in the position in which in it tightens of format is found "#", such figure will come copied in tightens of turns out to you. In contrary case, in it tightens of turns out to you will not come memorizzato some value in such position.
. Separator decimates them The first character "," of tightens of format determines the position of the separator decimates them in the formattato value. Eventual ulterior characters "," come ignore to you.
, Rappresentazione and separator migliaia in scale of the numbers The character "." he has two functions. In the first place, if he tightens it of format contains a character "." between two segnaposti for figures (0 or #) and if on the left of the separator one decimate them of it are present, the output will introduce inserted separators of the migliaia between every group of three figures on the left of the separator decimate them. In the second place, if he tightens it of format contains one or more characters "." immediately on the left of the separator he decimates them, the number will come divided for 1000 many times how many are the characters "." before being formattato.
% Segnaposto for percentage The presence of a character "%" in one tightens of format makes yes that a number comes multiplied for 100 before being formattato. The appropriate symbol comes inserted in the same number in the position in which it has been inserted sign "%" in tightens of format.
E0
E 0
E-0
e0
e 0
e-0
Scientific notation If in it tightens of format is present one of the stringhe "and", "E ", "and -", "and", "e " or "and -" immediately continuation from at least a character "0", the number will come formattato using the notation scientific with one "and" or "and" inserted between the number and the exponent. The number of characters "0" who follow the pointer of the scientific notation determines the minimal number of figures to visualize in the output for the exponent. Form "E to you" and "e " they indicate that the exponent always must be preceded from a sign character (more or less). Form to you "and", "and -", "and" and "and -" they indicate that only the exponents denied to you must be preceded from a sign character.
\ Character escape In C # and C the character turned upside down bar ago yes that the successive character in tightens of format comes interpreted like sequence of escape. He comes used with traditional sequences of formattazione like "\n" (new line). In some languages it is necessary that the character of escape same is preceded from a character of escape when comes used like a literal value. In contrary case in phase of compilation the character will come interpreted like one sequence of escape. To use tightens it "\ \" in order to visualize the character "\". is noticed that this character of escape is not supported in Visual Basic. ControlChars supplies however the same functionality.
' ABC'
"ABC"
It tightens literal The simple or double characters enclosed between virgolette come copied in tighten of turn out to you in literal way and they do not influence on the formattazione.
; Separator of section The character ";" it is used in order to separate sections of positive values, denied to you to you and zero in tighten of format.
(other) All the other characters All the other characters come copied in tighten of turn out to you as literal values in the position in which they are brought back.

Examples of I use of stringhe of personalized numerical format

Example Output
( 12 ).ToString("000"); ( 12 ).ToString("###"); ( 12 ).ToString("0,000.00"); ( 123456.789 ).ToString("0,000.00"); ( 123456.789 ).ToString("0,###,###.00"); 012 12 0.012,00 123.456,79 0.123.456,79
( 123456789 ).ToString("0,,.####"); 12,34568
( 12 ).ToString("#%"); ( 0.5678 ).ToString("#.000%"); ( 0.5678 ).ToString("#.0%"); 1200% 56,780% 56,8%
( 123456789 ).ToString("###e0"); ( 123456789 ).ToString("###E0"); ( 123456789 ).ToString("###E 0"); ( 0.123456789 ).ToString("###E-0"); 123e6 123E6 123E 6 123E-6
( 123 ).ToString("Output is #"); Output is 123
( 12 ).ToString("Positive: 0,000.00;Negative: #"); ( -12 ).ToString("Positive: 0,000.00;Negative: #"); ( -12 ).ToString("Positive: 0,000.00;Negative: -#"); ( -0.1 ).ToString("Positive: 0,000.00;Negative: -#;Zero!"); Positive: 0.012,00 Negatives: 12 Negatives: -12 Zero!

Formattazione of date and hour

The formattazione of a DateTime type can be in shape standard (by means of the application of one style predefined) or custom (by means of a format specified from the customer)

The date of reference (dt) used in the following examples corresponds to the 25 Opens them 2007 to hours 14, 37 minuteren, 54 second and 309 millesimi and is defined like:

DateTime dt = new DateTime(2007, 4, 25, 14, 37, 54, 309);

Stringhe of DateTime format standard

The formattazione standard previews a single character between those including in the brought back table of continuation. If the identificatore of format is not contained in the table that follows, it will come generated an exception in phase of execution. If he tightens it of format is longer than a single character, he will come interpreted as one tightens of personalized format, even if the characters added to you are constituted from spaces.

Format Name Example Output
d Short date dt.ToString("d"); 25/04/2007
D Extensive date dt.ToString("D"); Wednesday 25 you open them 2007
t Short hour dt.ToString("t"); 14.37
T Extensive hour dt.ToString("T"); 14.37.54
f Date and complete hour (short hour) dt.ToString("f"); Wednesday 25 you open them 2007 14.37
F Date and complete hour (extensive hour) dt.ToString("f"); Wednesday 25 you open them 2007 14.37.54
g General (short hour) dt.ToString("g"); 25/04/2007 14.37
G General (extensive hour) dt.ToString("G"); 25/04/2007 14.37.54
M (or m) Month and day dt.ToString("m"); 25 you open them
R (or r) RFC 1123 dt.ToString("r"); Wed, 25 Apr 2007 14:37:54 GMT
s ISO 8601 dt.ToString("s"); 2007-04-25T14:37:54
u Universal dt.ToString("u"); 2007-04-25 14:37:54Z

In occasion of the formattazione of the date and the hour it does not come executed some jet lag conversion of. The conversion of the local date and the hour in Greenwich Mean Time must therefore be executed before using this identificatore of format.

U Universal dt.ToString("U"); Wednesday 25 you open them 2007 12.37.54

The visualized hour is that standard, not that premises, and is equivalent to the DateTime value.

Y (or y) Year (year) and month dt.ToString("y"); you open them 2007

Stringhe of personalized DateTime format

It is possible to exercise a greater control on the formattazione of format a DateTime object using identificatori personalizes (you see following table to you)

Format Description Example Output
d Day of month (1 number) dt.ToString("%d"); ( new DateTime(2007, 4, 3) ).ToString("%d"); 25 3
dd Day of the month (2 figures) dt.ToString("dd"); ( new DateTime(2007, 4, 3) ).ToString("dd"); 25 03
ddd Day of the week (abbreviated) dt.ToString("ddd"); mer
dddd Day of the week (extended) dt.ToString("dddd"); Wednesday
f Fraction of second (1 number, zeri visualizes to you) dt.ToString("%f"); 3
ff Fraction of second (2 figures, zeri visualizes to you) dt.ToString("ff"); 30
fff Fraction of second (3 figures, zeri visualizes to you) dt.ToString("fff"); 309
ffff Fraction of second (4 figures, zeri visualizes to you) dt.ToString("ffff"); 3090
fffff Fraction of second (5 figures, zeri visualizes to you) dt.ToString("fffff"); 30900
ffffff Fraction of second (6 figures, zeri visualizes to you) dt.ToString("ffffff"); 309000
fffffff Fraction of second (7 figures, zeri visualizes to you) dt.ToString("fffffff"); 3090000
F Fraction of second (1 number, omitted zeri) dt.ToString("%F"); 3
FF Fraction of second (2 figures, omitted zeri) dt.ToString("FF"); 3
FFF Fraction of second (3 figures, omitted zeri) dt.ToString("FFF"); 309
FFFF Fraction of second (4 figures, omitted zeri) dt.ToString("FFFF"); 309
FFFFF Fraction of second (5 figures, omitted zeri) dt.ToString("FFFFF"); 309
FFFFFF Fraction of second (6 figures, omitted zeri) dt.ToString("FFFFFF"); 309
FFFFFFF Fraction of second (7 figures, omitted zeri) dt.ToString("FFFFFFF"); 309
g (or gg) It was (a.C./d.C.) dt.ToString("%g"); dt.ToString("gg"); d.C. d.C.
h Hour (1 number, 1-12) dt.ToString("%h"); 2
hh Hour (2 figures, 1-12) dt.ToString("hh"); 02
H Hour (1 number, 0-23) dt.ToString("%H"); ( new DateTime(2007, 4, 25, 9, 5, 7) ).ToString("%H"); 14 9
HH Hour (2 figures, 0-23) dt.ToString("HH"); ( new DateTime(2007, 4, 25, 9, 5, 7) ).ToString("HH"); 14 09
m Minuteren (1 number) dt.ToString("%m"); ( new DateTime(2007, 4, 25, 9, 5, 7) ).ToString("%m"); 37 5
milimeter Minuteren (2 figures) dt.ToString("mm"); ( new DateTime(2007, 4, 25, 9, 5, 7) ).ToString("mm"); 37 05
M Month (1 number) dt.ToString("%M"); 4
MILIMETER Month (2 figures) dt.ToString("MM"); 04
MMM Month (abbreviated) dt.ToString("MMM"); apr
MMMM Month (extended) dt.ToString("MMMM"); you open them
s Second (1 number) dt.ToString("%s"); ( new DateTime(2007, 4, 25, 9, 5, 7) ).ToString("%s"); 54 7
ss Second (2 figures) dt.ToString("ss"); ( new DateTime(2007, 4, 25, 9, 5, 7) ).ToString("ss"); 54 07
t Pointer AM/PM (first character) DateTimeFormatInfo fi = new DateTimeFormatInfo();
fi.AMDesignator = "Mattina";
fi.PMDesignator = "Pomeriggio";
dt.ToString("%t");
P

The formulations of default of the Italian culture do not preview no symbol of identification for AM and PM. In the example it has been therefore used a DateTimeFormatInfo in order to force the visualization of this format.

tt Pointer AM/PM (complete) DateTimeFormatInfo fi = new DateTimeFormatInfo();
fi.AMDesignator = "Mattina";
fi.PMDesignator = "Pomeriggio";
dt.ToString("tt");
Afternoon

The formulations of default of the Italian culture do not preview no symbol of identification for AM and PM. In the example it has been therefore used a DateTimeFormatInfo in order to force the visualization of this format.

y Year (1 number) dt.ToString("%y"); 7
yy Year (2 figures) dt.ToString("yy"); 07
yyyy Year (4 figures) dt.ToString("yyyy"); 2007
z Hours of jet lag (1 it number) dt.ToString("%z"); 2
zz Hours of jet lag (2 figures) dt.ToString("zz"); 02
zzz Hours and minuteren of jet lag dt.ToString("zzz"); 02:00
: Separator of the hour dt.ToString("%:"); .
/ Separator of the date dt.ToString("%/"); /
"ABC" (or ' ABC') Literal value dt.ToString("'d'"); d

You notice yourself that in I use of the format characters personalizes to you constituted from a single character turns out necessary to put in front character % in order to distinguish them from the identificatori of format standards (if available like as an example for "d", "f", "F" or "g"; if to the single character a format does not correspond standard and character "%" omits itself comes generated an exception of FormatException type)

Arranging or more identificatori than formed he personalizes can itself be constructed one outline to you of formattazione in a position to giving back the output wished:

Example Output
dt.ToString("'Ora corrente:' HH:mm:ss"); Running hour: 14.37.54
dt.ToString("dddd d MMMM yyyy - HH:mm:ss (z)"); Wednesday 25 you open them 2007 - 14.37.54 ( 2)

Formattazione of enumeratori

It is possible to use the ToString method in order to create a new object it tightens that it represents the numerical value, esadecimale or tightens of a Enum using tightens them of formattazione available (you see following table):

The enumeratore of reference (Colors) used in the following examples is defined like:

public enum Colors
{
    Default = 0,
    White = 1,
    Blue = 2,
    Red = 3,
    Black = 4
}
Format Name Example Output
G (or g) General Colors.Red.ToString("g"); Red

It visualizes the voice of enumeration under shape of value of tightens, if possible. In contrary case, it visualizes the value integer of the running request. If the enumeration comes defined with set up the Flags attribute, the values of tighten of ciascuna valid voice will be concatena between they, separate to you to you from virgole. If the Flags attribute is not set up, a not valid value will come visualized under shape of numerical voice.

F (or f) It tightens Colors.Red.ToString("f"); Red
D (or d) Entire Colors.Red.ToString("d"); 3
X (or x) Esadecimale (8 figures) Colors.Red.ToString("x"); 00000003