Строки стандартных числовых форматов 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Строки стандартных числовых форматов



Строки стандартных числовых форматов служат для форматирования стандартных числовых типов. Стандартная строка числового формата имеет вид Axx, где A является символом буквы, называемой спецификатором, а xx является опциональным целым числом, называемым спецификатором точности. Спецификатор точности находится в диапазоне от 0 до 99 и влияет на число цифр в результате. Любая строка числового формата, содержащая более одной буквы, включая пробелы, интерпретируется как строка пользовательского числового формата.

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

 


 

Format specifier Name Description
C or c Currency The number is converted to a string that represents a currency amount. The conversion is controlled by the currency format information of the current NumberFormatInfo object. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision given by the current NumberFormatInfo object is used. The following example formats a Double value with the currency format specifier.
double value = 12345.6789; Console.WriteLine(value.ToString("C", CultureInfo.InvariantCulture)); // Displays 12,345.68   Console.WriteLine(value.ToString("C3", CultureInfo.InvariantCulture)); // Displays 12,345.679   Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("en-US"))); // Displays $12,345.679

 


 

Описатель формата Имя Описание
C или c Валюта Число преобразуется в строку, представляющую денежные единицы. Преобразование регулируется сведениями о форматировании денежных единиц текущего объекта NumberFormatInfo. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, используется значение по умолчанию объекта NumberFormatInfo. В следующем примере значение Double форматируется с помощью спецификатора денежного формата.

ß------------


 

D or d Decimal This format is supported only for integral types. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. The following example formats an Int32 value with the Decimal format specifier.
int value;   value = 12345; Console.WriteLine(value.ToString("D")); // Displays 12345 Console.WriteLine(value.ToString("D8")); // Displays 00012345   value = -12345; Console.WriteLine(value.ToString("D")); // Displays -12345 Console.WriteLine(value.ToString("D8")); // Displays -00012345

 


 

D или d Десятичное число Этот формат доступен только для целых типов. Число преобразуется в строку, состоящую из десятичных цифр (0-9); если число отрицательное, перед ним ставится знак "минус". Минимальное количество знаков в выходной строке задается спецификатором точности. Недостающие знаки в строке заменяются нулями. В следующем примере значение Int32 форматируется с помощью спецификатора десятичного формата.

ß---------


 

E or e Scientific (exponential) The number is converted to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. One digit always precedes the decimal point. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used. The case of the format specifier indicates whether to prefix the exponent with an 'E' or an 'e'. The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required. The following example formats a Double value with the scientific format specifier.
double value = 12345.6789; Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture)); // Displays 1.234568E+004   Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture)); // Displays 1.2345678900E+004   Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture)); // Displays 1.2346e+004   Console.WriteLine(value.ToString("E", CultureInfo.CreateSpecificCulture("fr-FR"))); // Displays 1,234568E+004  

 


 

E или e Научный (экспоненциальный) Число преобразуется в строку вида "-d.ddd…E+ddd" or "-d.ddd…e+ddd», где знак "d" представляет цифру (0-9). Если число отрицательное, в начале строки появляется знак "минус". Перед разделителем целой и дробной части всегда стоит один знак. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, по умолчанию число знаков дробной части равно шести. Регистр спецификатора формата задает регистр буквы, стоящей перед экспонентой ("E" или "e"). Экспонента состоит из знака "плюс" или "минус" и трех цифр. Недостающие до минимума цифры заменяются нулями, если это необходимо. В следующем примере значение Double форматируется с помощью спецификатора экспоненциального формата.

ß---------------


 

F or f Fixed-point The number is converted to a string of the form "-ddd.ddd…" where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision is given by the NumberDecimalDigits property of the current NumberFormatInfo object. The following example formats a Double and an Int32 value with the fixed-point format specifier.
int integerNumber; integerNumber = 17843; Console.WriteLine(integerNumber.ToString("F", CultureInfo.InvariantCulture)); // Displays 17843.00   integerNumber = -29541; Console.WriteLine(integerNumber.ToString("F3", CultureInfo.InvariantCulture)); // Displays -29541.000   double doubleNumber; doubleNumber = 18934.1879; Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture)); // Displays 18934.19   Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture)); // Displays 18934   doubleNumber = -1898300.1987; Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture)); // Displays -1898300.2   Console.WriteLine(doubleNumber.ToString("F3", CultureInfo.CreateSpecificCulture("es-ES"))); // Displays -1898300,199  

 


 

F или f Фиксированная запятая Число преобразуется в строку вида "-ddd.ddd…", где знак "d" представляет цифру (0-9). Если число отрицательное, в начале строки появляется знак "минус". Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, по умолчанию точность числа задается свойством NumberDecimalDigits текущего объекта NumberFormatInfo. В следующем примере значение Double и значение Int32 форматируются с помощью спецификатора формата с фиксированной точкой.

ß-------


 

G or g General The number is converted to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated by the following list. · Byte or SByte: 3 · Int16 or UInt16: 5 · Int32 or UInt32: 10 · Int64 or UInt64: 19 · Single: 7 · Double: 15 · Decimal: 29 Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and less than the precision specifier; otherwise, scientific notation is used. The result contains a decimal point if required and trailing zeroes are omitted. If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, then the excess trailing digits are removed by rounding. The exception to the preceding rule is if the number is a Decimal and the precision specifier is omitted. In that case, fixed-point notation is always used and trailing zeroes are preserved. If scientific notation is used, the exponent in the result is prefixed with 'E' if the format specifier is 'G', or 'e' if the format specifier is 'g'. The following example formats assorted floating-point values with the general format specifier.  

 


 

G или g Общий Число преобразуется в наиболее короткую запись из записи с фиксированной запятой или экспоненциальной записи, в зависимости от типа числа и наличия спецификатора точности. Если спецификатор точности не задан или равен нулю, точность задается типом переменной, как показано в следующем списке. · Byte или SByte: 3 · Int16 или UInt16: 5 · Int32 или UInt32: 10 · Int64 или UInt64: 19 · Single: 7 · Double: 15 · Decimal: 29 Нотация с фиксированной запятой используется, если экспонента результата в экспоненциальной нотации длиннее пяти знаков, но меньше спецификатора точности, в противном случае используется научная нотация. Результат содержит разделитель целой и дробной частей, последние нули дробной части отбрасываются. Если спецификатор точности задан и число значащих цифр результата превосходит его значение, лишние знаки отбрасываются округлением. Составляется исключение из предыдущего правила, если число имеет тип Decimal и не указан спецификатор точности. В этом случае используется нотация с фиксированной запятой, последние нули дробной части сохраняются. Если используется научная нотация, регистр буквы, стоящей перед экспонентой задается регистром указателя формата (буква "E" соответствует "G", "e" соответствует "g"). В следующем примере различные значения с плавающей запятой форматируются с помощью спецификатора общего формата.

 

double number;

 

number = 12345.6789;

Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));

// Displays 12345.6789

Console.WriteLine(number.ToString("G",

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

// Displays 12345,6789

 

Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));

// Displays 12345.68

 

number =.0000023;

Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));

// Displays 2.3E-06

Console.WriteLine(number.ToString("G",

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

// Displays 2,3E-06

 

number =.0023;

Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));

// Displays 0.0023

 

number = 1234;

Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));

// Displays 1.2E+03

 

number = Math.PI;

Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));

// Displays 3.1416

 


 

double number;

 

number = 12345.6789;

Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));

// Displays 12345.6789

Console.WriteLine(number.ToString("G",

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

// Displays 12345,6789

 

Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));

// Displays 12345.68

 

number =.0000023;

Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));

// Displays 2.3E-06

Console.WriteLine(number.ToString("G",

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

// Displays 2,3E-06

 

number =.0023;

Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));

// Displays 0.0023

 

number = 1234;

Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));

// Displays 1.2E+03

 

number = Math.PI;

Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));

// Displays 3.1416


 

N or n Number The number is converted to a string of the form "-d,ddd,ddd.ddd…", where '-' indicates a negative number symbol if required, 'd' indicates a digit (0-9), ',' indicates a thousand separator between number groups, and '.' indicates a decimal point symbol. The actual negative number pattern, number group size, thousand separator, and decimal separator are specified by the NumberNegativePattern, NumberGroupSizes, NumberGroupSeparator, and NumberDecimalSeparator properties, respectively, of the current NumberFormatInfo object. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision is given by the NumberDecimalDigits property of the current NumberFormatInfo object. The following example formats assorted floating-point values with the number format specifier.
double dblValue = -12445.6789; Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture)); // Displays -12,445.68 Console.WriteLine(dblValue.ToString("N1", CultureInfo.CreateSpecificCulture("sv-SE"))); // Displays -12445,7   int intValue = 123456789; Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture)); // Displays 123,456,789.0

 

 


 

N или n Число Число преобразуется в строку вида "-d,ddd,ddd.ddd…», где знак '-' при необходимости представляет знак "минус", знак "d" - цифра (0-9), знак "," - разделитель тысяч, а знак "" - разделитель целой и дробной части. Фактический шаблон отрицательного числа, размер групп числа, разделитель тысяч и десятичный разделитель задаются свойствамиNumberNegativePattern, NumberGroupSizes, NumberGroupSeparator и свойством NumberDecimalSeparator, соответственно, текущего объекта NumberFormatInfo. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, по умолчанию точность числа задается свойством NumberDecimalDigits текущего объекта NumberFormatInfo. В следующем примере различные значения с плавающей запятой форматируются с помощью спецификатора числового формата.

ß-----------


 

P or p Percent The number is converted to a string that represents a percent as defined by the NumberFormatInfo..::.PercentNegativePattern property if the number is negative, or the NumberFormatInfo..::.PercentPositivePattern property if the number is positive. The converted number is multiplied by 100 in order to be presented as a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the current NumberFormatInfo object is used. The following example formats floating-point values with the percent format specifier.
double number =.2468013; Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture)); // Displays 24.68 % Console.WriteLine(number.ToString("P", CultureInfo.CreateSpecificCulture("hr-HR"))); // Displays 24.7 % Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture)); // Displays 24,68%  

 

 


 

P или p Процент Число преобразуется в строку, представляющую проценты, как определено свойством NumberFormatInfo..::.PercentNegativePattern, если число отрицательно, или свойством NumberFormatInfo..::.PercentPositivePattern, если число положительно. Преобразуемое число умножается на 100, чтобы соответствовать процентам. Требуемое число знаков дробной части задается спецификатором точности. Если спецификатор точности отсутствует, то используется значение по умолчанию объекта NumberFormatInfo. В следующем примере значения с плавающей запятой форматируются с помощью спецификатора процентного формата.

ß------------


 

R or r Round-trip This format is supported only for the Single and Double types. The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. Although a precision specifier can be present, it is ignored. Round trips are given precedence over precision when using this specifier. The following example formats Double values with the round-trip format specifier.
double value;   value = Math.PI; Console.WriteLine(value.ToString("r")); // Displays 3.1415926535897931 Console.WriteLine(value.ToString("r", CultureInfo.CreateSpecificCulture("fr-FR"))); // Displays 3,1415926535897931 value = 1.623e-21; Console.WriteLine(value.ToString("r")); // Displays 1.623E-21

 

 


 

R или r Приемо-передача Этот формат поддерживается только для типа Single и для типа Double. Этот спецификатор гарантирует, что отформатированное строковое значение будет разобрано в то же самое числовое значение. При форматировании числового значения с помощью этого спецификатора сначала производится форматирование в общий формат с 15 значащими цифрами для переменных типа Double и 7 значащими цифрами для переменных типа Single. Если строка может быть разобрана так, чтобы переменная приняла то же значение, форматирование производится с помощью общего указателя формата. Однако если разбор изменяет значение переменной, то количество значащих цифр увеличивается до 17 для типа Double и 9 значащих цифр для типа Single. Даже если спецификатор точности будет присутствовать, то он будет проигнорирован. Приведенные указатели приема-передачи в данном случае имеют преимущество перед указателем точности. В следующем примере значения Double форматируются с помощью спецификатора формата приема-передачи.

ß--------------


 

X or x Hexadecimal This format is supported only for integral types. The number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for the hexadecimal digits greater than 9. For example, use 'X' to produce "ABCDEF", and 'x' to produce "abcdef". The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. The following example formats Int32 values with the hexadecimal format specifier.
int value;   value = 0x2045e; Console.WriteLine(value.ToString("x")); // Displays 2045e Console.WriteLine(value.ToString("X")); // Displays 2045E Console.WriteLine(value.ToString("X8")); // Displays 0002045E   value = 123456789; Console.WriteLine(value.ToString("X")); // Displays 75BCD15 Console.WriteLine(value.ToString("X2")); // Displays 75BCD15  

 

 


 

X или x Шестнадцатеричный Этот формат доступен только для целых типов. Число преобразуется в строку шестнадцатеричных знаков. Регистр шестнадцатеричных знаков, превосходящих 9, совпадает с регистром указателя формата. Например, чтобы отображать эти цифры в виде "ABCDEF", задайте указатель "X"; и указатель "x", чтобы получить "abcdef". Минимальное количество знаков в выходной строке задается спецификатором точности. Недостающие знаки в строке заменяются нулями. В следующем примере значения Int32 форматируются с помощью спецификатора шестнадцатеричного формата.

ß--------------


Notes

Control Panel Settings

The settings in the Regional and Language Options item in Control Panel influence the result string produced by a formatting operation. Those settings are used to initialize the NumberFormatInfo object associated with the current thread culture, and the current thread culture provides values used to govern formatting. Computers using different settings will generate different result strings.

In addition, if the CultureInfo..::.CultureInfo(String) constructor is used to instantiate a new CultureInfo object that represents the same culture as the current system culture, any customizations established by the Regional and Language Options item in Control Panel will be applied to the new CultureInfo object. You can use the CultureInfo..::.CreateSpecificCulture method to create a CultureInfo that does not reflect a system's customizations.

NumberFormatInfo Properties

Formatting is influenced by properties of the current NumberFormatInfo object, which is provided implicitly by the current thread culture or explicitly by the IFormatProvider parameter of the method that invokes formatting. Specify a NumberFormatInfo or CultureInfo object for that parameter.



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 131; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.17.79.60 (0.06 с.)