logo
CSharp_Prog_Guide

Примеры кода

В приведенном ниже примере одна строка создается с помощью составного форматирования, а другая — с помощью метода ToString. Оба способа форматирования дают идентичные результаты.

string FormatString1 = String.Format("{0:dddd MMMM}", DateTime.Now);

string FormatString2 = DateTime.Now.ToString("dddd MMMM");

Предположим, что сейчас май, а текущий день недели — четверг; тогда значение обеих строк для языка и региональных параметров "Английский (США)" в предыдущем примере будет равно Thursday May.

Метод Console.WriteLine обладает той же функциональностью, что и String.Format. Единственное различие между двумя методами состоит в том, что метод String.Format возвращает результат в виде строки, а Console.WriteLine записывает результат в выходной поток, связанный с объектом Console.

В следующем примере для форматирования значения переменной MyInt в виде денежной единицы используется метод Console.WriteLine.

int MyInt = 100;

Console.WriteLine("{0:C}", MyInt);

На тех компьютерах, где выбраны языковые и региональные параметры "Английский (США)", этот код будет выводить на консоль строку $100.00.

В следующем примере демонстрируется форматирование нескольких объектов, в том числе форматирование одного и того же объекта двумя разными способами.

string myName = "Fred";

String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}",

myName, DateTime.Now);

Результатом обработки приведенной выше строки станет строка "Name = Fred, hours = 07, minutes = 23", числа в которой соответствуют текущему времени.

The following examples demonstrate the use of alignment in formatting. The arguments that are formatted are placed between vertical bar characters (|) to highlight the resulting alignment.

string myFName = "Fred";

string myLName = "Opals";

int myInt = 100;

string FormatFName = String.Format("First Name = |{0,10}|", myFName);

string FormatLName = String.Format("Last Name = |{0,10}|", myLName);

string FormatPrice = String.Format("Price = |{0,10:C}|", myInt);

Console.WriteLine(FormatFName);

Console.WriteLine(FormatLName);

Console.WriteLine(FormatPrice);

FormatFName = String.Format("First Name = |{0,-10}|", myFName);

FormatLName = String.Format("Last Name = |{0,-10}|", myLName);

FormatPrice = String.Format("Price = |{0,-10:C}|", myInt);

Console.WriteLine(FormatFName);

Console.WriteLine(FormatLName);

Console.WriteLine(FormatPrice);

The preceding code displays the following to the console in the U.S. English culture. Different cultures display different currency symbols and separators.

First Name = | Fred|

Last Name = | Opals|

Price = | $100.00|

First Name = |Fred |

Last Name = |Opals |

Price = |$100.00 |

Ниже приведен пример использования выравнивания при форматировании. Форматируемые аргументы разделены знаками вертикальной черты ("|"), подчеркивающими полученное выравнивание.

--------------

При выборе языка и региональных параметров "Английский (США)" этот код выведет на консоль следующий текст. При выборе различных языковых и региональных параметров знаки денежных единиц и разделители также различаются.

First Name = | Fred|

Last Name = | Opals|

Price = | $100.00|

First Name = |Fred |

Last Name = |Opals |

Price = |$100.00 |

Numeric Format Strings

Numeric format strings control formatting operations in which a numeric data type is represented as a string.

Numeric format strings fall into two categories:

Standard numeric format strings consist of one of a set of standard numeric format specifiers. Each standard format specifier denotes a particular, commonly used string representation of numeric data.

Custom format strings consist of one or more custom numeric format specifiers. Combine custom numeric format specifiers to define an application-specific pattern that determines how numeric data is formatted.

Numeric format strings are supported by the ToString method of numeric types. Numeric format strings are also supported by the .NET Framework composite formatting feature, which is used by certain Write and WriteLine methods of the Console and StreamWriter classes, the String..::.Format method, and the StringBuilder..::.AppendFormat method.

Standard Numeric Format Strings

Standard numeric format strings are used to format common numeric types. A standard numeric format string takes the form Axx, where A is an alphabetic character called the format specifier, and xx is an optional integer called the precision specifier. The precision specifier ranges from 0 to 99 and affects the number of digits in the result. Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string.

The following table describes the standard numeric format specifiers and displays sample output produced by each format specifier. For more information, see the notes that follow the table.