logo search
CSharp_Prog_Guide

Форматирование базовых типов

Форматирование служит для преобразования стандартных типов данных .NET Framework в строку и последующего отображения. Например, чтобы отобразить целое значение 100 в виде денежных единиц, воспользуйтесь методом ToString и строкой формата денежных единиц ("С"), чтобы создать строку "$100.00". Обратите внимание, что на компьютерах с выбранным языком и региональными параметрами, отличным от "Английского (США)", эта строка будет отображена в условных единицах установленного языком и региональными параметрами.

Чтобы отформатировать базовый тип, при вызове метода ToString для требуемого вида следует задать спецификатор формата и/или поставщика формата. Если спецификатор формата не задан или в качестве параметра передано значение null, то по умолчанию будет использован указатель "G" (общий формат). Если поставщик формата не задан, или в качестве параметра передано значение null, или если для поставщика не заданы требуемые для выполнения форматирования свойства, то будет использован поставщик формата, связанный с текущим потоком.

В следующем примере метод ToString показывает значение 100 как строку денежного формата на консоли.

int MyInt = 100;

String MyString = MyInt.ToString("C");

Console.WriteLine(MyString);

Formatting for Different Cultures

For most methods, the values returned using one of the string format specifiers have the ability to dynamically change based on the current culture or a specified culture. For example, an overload of the ToString method accepts a format provider that implements the IFormatProvider interface. Classes that implement this interface can specify characters to use for decimal and thousand separators and the spelling and placement of currency symbols. If you do not use an override that takes this parameter, the ToString method will use characters specified by the current culture.

The following example uses the CultureInfo class to specify the culture that the ToString method and format string will use. This code creates a new instance of the CultureInfo class called MyCulture and initializes it to the French culture using the string fr-FR. This object is passed to the ToString method with the C string format specifier to produce a French monetary value.

int MyInt = 100;

CultureInfo MyCulture = new CultureInfo("fr-FR");

String MyString = MyInt.ToString("C", MyCulture);

Console.WriteLine(MyString);

The preceding code displays 100,00 when displayed in a Windows Forms form. Note that the console environment does not support all Unicode characters and displays 100,00 ? instead.