Floating-Point Infinities and NaN



Note that regardless of the format string, if the value of a Single or Double floating-point type is positive infinity, negative infinity, or Not a Number (NaN), the formatted string is the value of the respective PositiveInfinitySymbol, NegativeInfinitySymbol, or NaNSymbol property specified by the currently applicable NumberFormatInfo object.

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.

Rounding and Fixed-Point Format Strings

Note that for fixed-point format strings (that is, format strings that do not contain scientific notation format characters), numbers are rounded to as many decimal places as there are digit placeholders to the right of the decimal point. If the format string does not contain a decimal point, the number is rounded to the nearest integer. If the number has more digits than there are digit placeholders to the left of the decimal point, the extra digits are copied to the result string immediately before the first digit placeholder.

 


Примечания

Бесконечности действительных чисел с плавающей запятой и NaN

Обратите внимание, что независимо от строки формата, если значение типа с плавающей запятойSingle или Double является плюс бесконечностью, минус бесконечностью или не является числом (NaN), в отформатированной строке является значением соответствующим PositiveInfinitySymbol, NegativeInfinitySymbol, или свойству NaNSymbol, которые указаны в данный момент соответствующим объектом NumberFormatInfo.

Настройки панели управления

Параметры элемента панели управления Язык и региональные стандарты влияют на выходную строку, получаемую в результате операции форматирования. Эти параметры используются для инициализации объекта NumberFormatInfo, связанного с текущей культурой потока, а текущая культура потока предоставляет значения, которые используются для управления форматированием. Результирующие строки будут различаться на компьютерах с разными настройками.

Строки формата с фиксированной запятой и округлением

Обратите внимание, что строки формата с фиксированной запятой (т.е. не содержащие символов экcпоненциального представления) округляют значение с точностью, заданной количеством знаков-заместителей справа от десятичной точки. Если в строке формата нет десятичной точки, то число округляется до ближайшего целого значения. Если слева от десятичной точки больше цифр, чем знаков-заместителей цифр, то лишние знаки копируются в выходную строку перед первым знаком-заместителем цифры.

 


Section Separators and Conditional Formatting

Different formatting can be applied to a string based on whether the value is positive, negative, or zero. To produce this behavior, a custom format string can contain up to three sections separated by semicolons. These sections are described in the following table.

Number of sections Description
One section The format string applies to all values.
Two sections The first section applies to positive values and zeros, and the second section applies to negative values. If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, then the resulting zero is formatted according to the first section.
Three sections The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros. The second section can be left empty (by having nothing between the semicolons), in which case the first section applies to all nonzero values. If the number to be formatted is nonzero, but becomes zero after rounding according to the format in the first or second section, then the resulting zero is formatted according to the third section.

Section separators ignore any preexisting formatting associated with a number when the final value is formatted. For example, negative values are always displayed without a minus sign when section separators are used. If you want the final formatted value to have a minus sign, you should explicitly include the minus sign as part of the custom format specifier.

The following code fragments illustrate how section separators can be used to produce formatted strings.

 


Разделители секций и условное форматирование[20]

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

Число секций Описание
Одна секция Строка форматирования применяется ко всем значениям.
Две секции Первая секция применяется для положительных значений и нулей, вторая секция применяется для отрицательных значений. Если форматируемое число является отрицательным, но становится нулем в результате округления в соответствии с форматированием, то ноль форматируется в соответствии с первой секцией.
Три секции Первая секция применяется для положительных значений, вторая секция применяется для отрицательных значений, а третья — для нулей. Вторая секция может быть пустой (между двумя точками с запятой пусто), в этом случае первая секция будет использоваться для форматирования нулевых значений. Если форматируемое число является ненулевым, но становится нулем в результате округления в соответствии с форматированием в первой или второй секции, то ноль форматируется в соответствии с третьей секцией.

При форматировании конечного значения разделители секций игнорируют любое существовавшее ранее форматирование, связанное с числом. Например, при использовании разделителей секций отрицательные значения всегда отображаются без знака "минус". Чтобы конечное отформатированное значение содержало знак "минус", его следует явным образом включить в настраиваемый спецификатор формата.

В следующих фрагментах кода демонстрируется применение разделителей секций для создания строк форматирования.


 

double MyPos = 19.95, MyNeg = -19.95, MyZero = 0.0;

 

// In the U.S. English culture, MyString has the value: $19.95.

string MyString = MyPos.ToString("$#,##0.00;($#,##0.00);Zero");

 

// In the U.S. English culture, MyString has the value: ($19.95).

// The minus sign is omitted by default.

MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero");

 

// In the U.S. English culture, MyString has the value: Zero.

MyString = MyZero.ToString("$#,##0.00;($#,##0.00);Zero");

Two Custom Format Examples

The following code fragments demonstrate custom numeric formatting. In both cases the digit placeholder (#) in the custom format string displays the numeric data, and all other characters are copied to the output.

Double myDouble = 1234567890; String myString = myDouble.ToString( "(###) ### - ####" ); // The value of myString is "(123) 456 – 7890".   int MyInt = 42; MyString = MyInt.ToString( "My Number = #" ); // In the U.S. English culture, MyString has the value: // "My Number = 42".

 


 


Дата добавления: 2019-03-09; просмотров: 249; Мы поможем в написании вашей работы!

Поделиться с друзьями:






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