C # string format example

Source: Internet
Author: User
Tags iso 8601 month name rounds
String. format description C # format the value result table

Character

Description

Example

Output

C Currency String. Format ("{0: C3}", 2) $2.000
D Decimal String. Format ("{0: D3}", 2) 002
E Scientific notation 1.20e + 001 1.20e + 001
G General String. Format ("{0: g}", 2) 2
N Number separated by semicolons String. Format ("{0: n}", 250000) 250,000.00
X Hexadecimal String. Format ("{0: x000}", 12) C


String. Format ("{0: 000. 000}", 12.2) 012.200
Strings

There really isn't any formatting within a strong, beyond it's alignment. Alignment works for any argument being printed in a string. Format call.

 

Sample Generates
String. Format ("->{1,10} <-", "hello "); -> Hello <-
String. Format ("-> {1,-10} <-", "hello "); -> Hello <-
Numbers

Basic number formatting specifiers:

 

Specifier Type Format

Output
(Passed
Double 1.42)

Output
(Passed
INT-12400)

C Currency {0: c} $1.42 -$12,400
D Decimal (whole number) {0: d} System.
Formatexception
-12400
E Scientific {0: e} 1.420000e + 000 -1.2420.e + 004
F Fixed Point {0: f} 1.42 -12400.00
G General {0: g} 1.42 -12400
N Number with commas for thousands {0: n} 1.42 -12,400
R Round trippable {0: R} 1.42 System.
Formatexception
X Hexadecimal {0: X4} System.
Formatexception
Cf90

Custom number formatting:

 

Specifier Type Example Output (passed dual 1500.42) Note
0 Zero placeholder {. 0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0 :(#).##} (1500). 42
. Decimal point {0. 0} 1500.4
, Thousand Separator {0: 0, 0} 1,500 Must be between two zeroes.
,. Number Scaling {0: 0 ,.} 2 Comma adjacent to period scales by 1000.
% Percent {0: 0%} 150042% Multiplies by 100, adds % sign.
E Exponent placeholder {0: 00e + 0} 15e + 2 Specified exponent formats available.
; Group Separator See below

The Group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses. This currency formatting example at the bottom of this document makes it obvious:

Dates

Note that date formatting is especially dependant on the system's regional settings; the example strings here are from my local locale.

 

Specifier Type Example (passed system. datetime. Now)
D Short date 10/12/2002
D Long date December 10,200 2
T Short Time 10: 11 pm
T Long time 10:11:29
F Full Date & time December 10,200 2 pm
F Full Date & time (long) December 10,200 2 10:11:29
G Default Date & time 10/12/2002 pm
G Default Date & time (long) 10/12/2002 10:11:29
M Month day Pattern December 10
R Rfc1123 date string Tue, 10 Dec 2002 22:11:29 GMT
S Sortable date string 2002-12-10t22: 11: 29
U Universal sortable, local time 2002-12-10 22: 13: 50z
U Universal sortable, GMT December 11,200 2 3:13:50 AM
Y Year month pattern December 2002

The 'U' specifier seems broken; that string certainly isn' t sortable.

Custom date formatting:

 

Specifier Type Example Example output
Dd Day {0: dd} 10
Ddd Day name {0: DDD} Tue
Dddd Full day name {0: dddd} Tuesday
F, FF ,... Second Fractions {0: fff} 932
GG ,... Era {0: Gg} A.D.
HH 2 digit hour {0: hh} 10
HH 2 digit hour, 24hr format {0: hh} 22
Mm Minute 00-59 {0: mm} 38
Mm Month 01-12 {0: mm} 12
Mmm Month abbreviation {0: Mmm} Dec
Mmmm Full month name {0: Mmmm} December
SS Seconds 00-59 {0: SS} 46
TT AM or PM {0: TT} PM
YY Year, 2 digits {0: yy} 02
Yyyy Year {0: yyyy} 2002
Zz Timezone offset, 2 digits {0: ZZ} -05
Zzz Full timezone offset {0: ZZZ} -05:00
: Separator {0: hh: mm: SS} 10:43:20
/ Separator {0: dd/mm/yyyy} 10/12/2002
Enumerations

 

Specifier Type
G Default (flag names if available, otherwise decimal)
F Flags always
D Integer always
X Eight digit hex.
Some useful examples

String. Format ("{0 :$ #,## 0.00; ($ #,## 0.00); zero}", value );

This will output "$1,240.00" if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string "zero" if the number is zero.

String. Format ("{0 :( ###) #######}", 18005551212 );

This will output "(800) 555-1212 ".

 

Variable. tostring ()

Convert string to string
12345. tostring ("N"); // generate 12,345.00
12345. tostring ("C"); // generate $12,345.00
12345. tostring ("e"); // generate 1.234500e + 004
12345. tostring ("F4"); // generate 12345.0000
12345. tostring ("X"); // generate 3039 (hexadecimal)
12345. tostring ("p"); // generate 1,234,500.00%

This is often used to format strings of dates and numbers, so we sorted out some of the help items here.

The following table describes the standard format specifiers used to format datetime objects.
Format description
D. The short date mode displays the mode defined by the datetimeformatinfo. shortdatepattern attribute associated with the current thread or the mode defined by the provider in the specified format.
D. The long date mode displays the mode defined by the datetimeformatinfo. longdatepattern attribute associated with the current thread or the mode defined by the provider in the specified format.
T short-time mode displays the mode defined by the datetimeformatinfo. effectimepattern attribute associated with the current thread or the mode defined by the provider in the specified format.
T long time mode displays the mode defined by the datetimeformatinfo. longtimepattern attribute associated with the current thread or the mode defined by the provider in the specified format.
F. The combination of long date and short time modes is displayed in full date/time mode (short time), separated by spaces.
F full date/time mode (long time) displays the mode defined by the datetimeformatinfo. fulldatetimepattern attribute associated with the current thread or the mode defined by the provider in the specified format.
G conventional date/time mode (Short Time) shows the combination of short date and short time mode, separated by spaces.
G regular date/time mode (long time) shows the combination of short date and long time mode, separated by spaces.
The m or M month/day mode displays the mode defined by the datetimeformatinfo. monthdaypattern attribute associated with the current thread or the mode defined by the provider in the specified format.
The R or R rfc1123 mode displays the mode defined by the datetimeformatinfo. rfc1123pattern attribute associated with the current thread or the mode defined by the provider in the specified format. This is the defined standard and the attribute is read-only. Therefore, it is always the same regardless of the culture or the provided format provider. The attribute references the cultureinfo. invariantculture attribute and follows the custom mode "DDD, DD Mmm yyyy hh: mm: SS g \ MT ". Note that "M" in "GMT" requires an escape character, so it is not interpreted. Formatting does not change the datetime value, so you must adjust the value to GMT before formatting.
S: sorted date/time mode. ISO 8601 is used to display the mode defined by the datetimeformatinfo. sortabledatetimepattern attribute associated with the current thread or the mode defined by the provider in the specified format. The attribute references the cultureinfo. invariantculture attribute. The format complies with the custom mode "yyyy-mm-ddthh: mm: SS ".
U common sortable date/time mode displays the mode defined by the datetimeformatinfo. universalsortabledatetimepattern attribute associated with the current thread or the mode defined by the provider in the specified format. Because it is a defined standard and its attributes are read-only, the pattern is always the same no matter what the regional or format provider is. The format follows the custom mode "yyyy-mm-dd hh: mm: SSZ ". The Time Zone is not converted when the date and time are formatted. Therefore, convert the local date and time to the common time before the format specifier is used.
The universal sorting date/time mode of U displays the mode defined by the datetimeformatinfo. fulldatetimepattern attribute associated with the current thread or the mode defined by the provider in the specified format. Note that the displayed time is the general time, not the local time.
Y or y year-on-year mode displays the mode defined by the datetimeformatinfo. yearmonthpattern attribute associated with the current thread or the mode defined by the provider in the specified format.
Unknown specifiers for any other single character

The following table describes the strings in the standard numeric format. Note that the output strings produced by these format specifiers are affected by the settings in the "region options" control panel. Computers with different settings will generate different output strings.

Format description
The C or C currency number is converted into a string that represents the monetary amount. Conversion is controlled by the currency format information of the numberformatinfo object used to format numbers. The precision specifier indicates the number of decimal places required. If the precision specifier is omitted, the default currency precision given by numberformatinfo is used.
D or D decimal only integer type supports this format. Convert a number to a string of a decimal number (0-9). If the number is negative, a negative sign is added. The precision specifier indicates the minimum number of digits required in the result string. If necessary, fill the left side of the number with zero to generate the number specified by the precision specifier.
E or E scientific notation (exponent) number to "-D. ddd... E + DDD "or"-D. ddd... E + DDD string, where each "D" represents a number (0-9 ). If this number is negative, the string starts with a minus sign. There is always a number before the decimal point. The precision specifier indicates the number of digits required after the decimal point. If the precision specifier is omitted, the default value is used, that is, six digits after the decimal point. The case description indicates whether to add the prefix "E" or "e" before the index ". An index is always composed of a positive or negative number and at least three digits. If needed, fill the index with zero to meet the requirements of at least three digits.
F or F fixed point numbers are converted to strings in the form of "-DDD...", where each "D" represents a number (0-9 ). If this number is negative, the string starts with a minus sign. The precision specifier indicates the number of decimal places required. If the precision specifier is ignored, the default numeric precision given by numberformatinfo is used.
G or G generally converts numbers into the most compact form of fixed points or scientific notation based on the number type and whether there is a precision specifier. If the precision specifier is omitted or zero, the default precision is determined by the number type, as shown in the following table.
Byte or sbyte: 3
Int16 or uint16: 5
Int32 or uint32: 10
Int64 or uint64: 19
Single: 7
Double: 15
Decimal: 29
If the index is greater than-5 and less than the precision specifier when the number is expressed in scientific notation, the fixed point notation is used; otherwise, the scientific notation is used. If a decimal point is required and Zero tail is ignored, the result contains the decimal point. If the precision specifier exists and the number of valid digits in the result exceeds the specified precision, the redundant trailing digits are deleted by rounding. When scientific notation is used, if the format specifier is "g", the result index carries the prefix "e"; if the format specifier is "g ", the index of the result is prefixed with "E ".

The preceding rule has one exception: if the number is decimal and the precision specifier is omitted. In this case, the fixed point notation is always used and the tail zero is retained.

Convert N or N numbers to strings in the "-D, DDD, DDD..." format, where each "D" represents a number (0-9 ). If this number is negative, the string starts with a minus sign. A thousands separator is inserted between every three digits on the left of the decimal point. The precision specifier indicates the number of decimal places required. If the precision specifier is ignored, the default numeric precision given by numberformatinfo is used.
The P or P percentage number is converted to a percent string defined by the numberformatinfo. percentnegativepattern attribute or the numberformatinfo. percentpositivepattern attribute. If the number is negative, the generated string is defined by percentnegativepattern and starts with a negative number. The converted number is multiplied by 100 as a percentage. The precision specifier indicates the number of decimal places required. If the precision specifier is omitted, the default numeric precision given by numberformatinfo is used.
The description of the round-trip process of R or R ensures that the value converted to a string is analyzed as the same value again. When formatting a value using this specifier, first use the regular format to test: Double uses 15-bit precision, and single uses 7-bit precision. If the value is successfully analyzed back to the same value, it is formatted using the regular format specifier. However, if this value is not successfully analyzed as the same value, it is formatted as follows: Double uses 17-bit precision, and single uses 9-bit precision. Although the precision specifier can be appended to the format specifier of the round-trip process, it will be ignored. When this specifier is used, the round-trip process takes precedence over precision. This format is only supported by the floating point type.
A string that converts X or X hexadecimal numbers to hexadecimal numbers. The case description indicates whether to use uppercase or lowercase letters for hexadecimal numbers greater than 9. For example, "X" is used to generate "abcdef" and "X" is used to generate "abcdef ". The precision specifier indicates the minimum number of digits required in the result string. If necessary, fill the left side of the number with zero to generate the number specified by the precision specifier. Only integer types support this format.

If the standard numeric format specifier does not provide the required formatting type, you can use a custom format string to further enhance the string output. A standard string contains a letter, followed by a sequence of numbers (forming a value ranging from 0 to 99), and all other format strings are custom format strings.
The following table shows the strings and characters that can be used to create custom numbers. Note that the setting of the "region options" control panel of the numberformatinfo object associated with the current thread affects some output strings of these characters. Computers in different regions will generate different output strings.
Description of Characters in the format
0 0 placeholder if the formatted value contains a number at the position of "0" in the format string, the number is copied to the output string. The leftmost "0" position before the decimal point and the rightmost "0" position after the decimal point determine the total number range in the output string. The "00" specifier rounds the value to the number nearest to the decimal point, and the zero digit is rounded off. For example, if "00" is used to format 34.5, the value 35 is obtained.
# Digit placeholder if the formatted value contains a number at the position of "#" in the format string, the number is copied to the output string. Otherwise, no value is stored in the output string. Note that if "0" is not a valid number, this specifier never displays "0", even if "0" is a unique number in the string. If "0" is a valid number in the displayed number, "0" is displayed. A string in the format of "#" rounds the value to the number nearest to the decimal point, with zero rounded off. For example, format 34.5 with "#" to get the value 35.
. The first "." character in the decimal point format string determines the location of the decimal point Separator in the formatted value. Any other "." characters are ignored. The actual Characters Used as the decimal separator are determined by the numberdecimalseparator attribute of the numberformatinfo.
, The thousands separator and numeric ratio conversion "," character has two purposes. First, if the format string contains the "," character between the two digit placeholders (0 or #) on the left of the decimal point (if any, the output will insert a thousands separator between every three digits on the left of the decimal separator. The actual characters used as decimal separator in the output string are determined by the numbergroupseparator attribute of the currently formatted numberformatinfo.
Second, if the format string contains one or more "," characters on the left side of the decimal point, the number is divided by "," and multiplied by 1000 before formatting. For example, the format string "0," represents 100,000,000 as 100. Use the "," character to indicate that the proportion conversion does not include the thousands Separator in the formatted number. Therefore, to reduce the number by 1,000,000 times and insert a thousands separator, use the format string "#, #0 ,,".
% Percent Placeholder "%" in the format string will cause the number to be multiplied by 100 before formatting. Insert the appropriate symbol to the position where the number itself appears "%" in the format string. The percentage characters used are determined by the current numberformatinfo class.
E0
E + 0
E-0
E0
E + 0
E-0 scientific notation if any string in "E", "e +", "e-", "e +", or "e-" appears in the Format String, and followed by at least one "0" character, the number is formatted using scientific notation, insert "E" or "e" between the number and the index ". The "0" Character Count following the scientific notation indicator determines the minimum number of digits of the exponential output. The symbols in the "e +" and "e +" formats (positive or negative) should always be placed before the index. The characters in the "e", "e-", "E", or "e-" format indicate that the symbols are placed before the negative index only.
The \ escape character is in the hosting extension of C # And C ++. The backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with a traditional formatting sequence, such as "\ n" (line feed ).
In some languages, the escape character must follow the escape character when used as text. Otherwise, the compiler considers the character as an escape character. Use the string "\" to display "\".
Note that this escape character is not supported in Visual Basic, but controlchars provides the same functions.
'Abc'
The characters enclosed in single or double quotation marks in the "ABC" string are copied to the output string as they are, and the format is not affected.
The ';' character is used to separate the positive, negative, and zero parts of the format string.
All other characters, all other characters, are copied as text to the position where they appear in the output string.

Please note that, for fixed point format strings (strings that do not contain E0, e + 0, E-0, E0, e + 0, or e-0 ), the number is rounded to the same number of decimal places as the number of digits to the right of the decimal point. If the format string does not contain the decimal point, the number is rounded to the nearest integer. If the number of digits is more than the number of digits on the left of the decimal point, the extra digits are copied to the output string and placed before the first digit placeholder.
You can apply different formatting methods to strings based on the values of positive, negative, or zero. To generate this behavior, a custom string can contain up to three parts separated by semicolons:
One part: the format string is applied to all values.
Two parts: the first part applies to positive and zero, and the second part applies to negative values. If the number to be formatted is negative but rounded to zero according to the format in the second part, the final zero is formatted according to the first part.
Three parts: The first part applies to positive values, the second part applies to negative values, and the third part applies to zero. The second part may be blank (there is no content between semicolons). In this case, the first part applies to all non-zero values. If the number to be formatted is a non-zero value, but is rounded to zero according to the format in the first or second part, the final zero is formatted according to the third part.
When formatting the final value, this type of formatting ignores all previous formats associated with numbers. For example, when some separators are used, the negative value never carries a negative number. If you want the formatted final value to have a negative number, you should explicitly include a negative number as part of the custom format specifier.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.