logo search
CSharp_Prog_Guide

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

Обратите внимание, что строки формата с фиксированной запятой (т.е. не содержащие символов эк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.