String. Format

Source: Internet
Author: User
Replace each format item in the specified string with the text equivalent item of the value of the corresponding object.

String Str1 = string. Format ("{0: N1}", 56789 ); // Result: 56,789.0
String Str2 = string. Format ("{0: N2}", 56789 ); // Result: 56,789.00
String Str3 = string. Format ("{0: N3}", 56789 );// Result: 56,789.000
String Str8 = string. Format ("{0: F1}", 56789 );// Result: 56789.0
 String Str9 = string. Format ("{0: F2}", 56789 );// Result: 56789.00
 String Str11 = (56789/100 .0). tostring ("#.##");// Result: 567.89
 StringStr12 = (56789/100). tostring ("#.##");// Result: 567

For a string in the standard numeric format, see
Formatting type | system. Globalization. numberformatinfo | custom numeric format string | standard numeric format string output example language
C #
 
Visual Basic
Show all
A string in the standard numeric format is used to format a common numeric value. The Standard Format String is in the form of "axx", where "A" is a single letter character (known as a format specifier), and "XX" is an optional INTEGER (known as a precision specifier ). The format description must be a built-in format character. The range of the precision specifier ranges from 0 to 99. It controls the number of valid digits or the number of digits to the right of the decimal point. The format string cannot contain spaces.
If the format string does not contain a standard format specifier, formatexception is thrown. For example, the format string "Z" is interpreted as a standard numeric string because it contains a letter character, but the letter character does not belong to the standard numeric format specifier, thus causing formatexception. Any numeric string that does not conform to the definition of a standard numeric string is interpreted as a custom numeric string. Format String "c !" It contains two letters, so it is interpreted as a custom string, although the character "C" is a standard digit format specifier.
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.
 
The following example illustrates how to format the base type of a number using a standard numeric format specifier.
[Visual Basic]
Imports system
Imports system. Globalization
Imports system. threading
 
Module module1
Sub main ()
Thread. currentthread. currentculture = new cultureinfo ("En-us ")
Dim mydouble as double = 123456789
 
Console. writeline ("the examples in en-US culture :")
Console. writeline (mydouble. tostring ("C "))
Console. writeline (mydouble. tostring ("e "))
Console. writeline (mydouble. tostring ("p "))
Console. writeline (mydouble. tostring ("N "))
Console. writeline (mydouble. tostring ("F "))
  thread. currentthread. currentculture = new cultureinfo ("de-de") 
console. writeline ("the examples in de-de culture:")
console. writeline (mydouble. tostring ("C")
console. writeline (mydouble. tostring ("e")
console. writeline (mydouble. tostring ("p")
console. writeline (mydouble. tostring ("N")
console. writeline (mydouble. tostring ("F")
end sub
end module
[C #]
using system;
using system. threading;
using system. globalization;
  class class1 
{< br> static void main ()
{< br> thread. currentthread. currentculture = new cultureinfo ("En-us");
double mydouble = 123456789;
console. writeline ("the examples in en-US culture. \ n ");
console. writeline (mydouble. tostring ("C");
console. writeline (mydouble. tostring ("e");
console. writeline (mydouble. tostring ("p");
console. writeline (mydouble. tostring ("N");
console. writeline (mydouble. tostring ("F");
Thread. currentthread. currentculture = new cultureinfo ("de-de ");
Console. writeline ("the examples in de-de culture. \ n ");
Console. writeline (mydouble. tostring ("C "));
Console. writeline (mydouble. tostring ("e "));
Console. writeline (mydouble. tostring ("p "));
Console. writeline (mydouble. tostring ("N "));
Console. writeline (mydouble. tostring ("F "));
}
}
AboveCode In this example, the following content is displayed on the console.
The examples in en-US culture:
$123,456,789.00
1.234568e + 008
12,345,678,900.00%
123,456,789.00
123456789.00
The examples in de-de culture:
123.456.789, 00 DM
1, 234568e + 008
12,345,678,900.00%
123.456.789, 00
123456789,00


 
For custom datetime format strings, see
Formatting type | system. datetime | system. iformatprovider | custom datetime Format String output example | standard datetime Format String Language
C #
 
Visual Basic
Show all
You can use the custom datetime format specifier to create your own custom datetime format string, you can better control the way to format datetime objects. Combine one or more custom format specifiers to construct the datetime formatting mode that can generate your favorite output. In fact, most of the standard datetime format specifiers are aliases of the formatting mode specified in the currently applicable datetimeformatinfo class.
The following table describes the custom format specifiers and their results. The output of these format specifiers is affected by the current culture and settings in the "region options" control panel.
Format description
D shows the current date of the month, represented by a number between 1 and 31, including 1 and 31. If the date has only one digit (1-9), it is displayed as a digit.
Note that if the "D" format specifier is used separately and there are no other custom format strings, it is interpreted as a standard short date format specifier. If the "D" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
Dd displays the current date of the month, represented by a number between 1 and 31, including 1 and 31. If the date has only one digit (1-9), format it with a leading 0 (01-09 ).
Ddd displays the abbreviation of the specified datetime date. If no specific valid format is provided Program (Implement a non-empty object of iformatprovider with the expected attributes), use the abbreviateddaynames attribute of datetimeformat and the current region associated with the currently used thread. Otherwise, use the abbreviateddaynames attribute from the specified format provider.
Dddd (plus any number of additional "D" characters) displays the date full name of the specified datetime. If no specific valid format provider is provided (a non-empty object can implement the iformatprovider with the expected attributes ), the daynames attribute of datetimeformat and the current culture associated with the currently used thread are used. Otherwise, use the daynames attribute from the specified format provider.
F indicates the second in one digit.
Note that if the "f" format specifier is used separately and there are no other custom format strings, it is interpreted as a complete (long date + short time) format specifier. If the "f" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
FF indicates the second in two digits.
Fff displays the seconds in three digits.
FFFF indicates the second in four digits.
Fffff displays the seconds in five digits.
Ffffff displays the seconds in six digits.
Fffffff displays the seconds in seven digits.
G or Gg (plus any number of additional "G" characters) shows the time of the specified datetime (for example, A. D .). If no specific valid format provider is provided (a non-empty object can implement the iformatprovider with the expected attributes ), the date is determined by the calendar associated with datetimeformat and the current culture associated with the current thread.
Note that if the "G" format specifier is used separately and there are no other custom format strings, it is interpreted as a standard regular format specifier. If the "G" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
H shows the hour of the specified datetime in the range of 1 to 12. This hour indicates the hour that has elapsed since midnight (displayed as 12) or noon (also displayed as 12. If this format is used separately, it cannot be different from the time before or after noon for an hour. If the hour is a single number (1-9), it is displayed as a single number. It indicates that no round occurs in the hour. For example, if datetime is, 5 is returned.
HH, HH (plus any number of additional "H" characters) displays the specified datetime hours in a number ranging from 1 to 12, which indicates that the hours are from midnight (displayed as 12) or the whole hour after noon (also displayed as 12. If this format is used separately, it cannot be different from the time before or after noon for an hour. If the hour is a single number (1-9), format it with 0 (01-09) in front ).
H is a number ranging from 0 to 23 to display the hour of the specified datetime. The hour indicates the whole hour that has elapsed since midnight (displayed as 0. If the hour is a single number (0-9), it is displayed as a single number.
HH, HH (plus any number of additional "H" characters) display the specified datetime hours in a number ranging from 0 to 23, which indicates that the hours are from midnight (displayed as 0) the total number of hours that follow. If the hour is a single number (0-9), format it with 0 (01-09) in front ).
M Displays the minutes of the specified datetime with a number ranging from 0 to 59. The minutes represent the whole minutes that have elapsed since the last hour. If the minute is a digit (0-9), it is displayed as a digit.
Note that if the "M" format specifier is used separately and there are no other custom format strings, it is interpreted as a standard month-day format specifier. If the "M" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
Mm, mm (plus any number of additional "M" characters) display the specified datetime minutes with a number ranging from 0 to 59, the number of minutes indicates the number of minutes that have elapsed since the last hour. If the minute is a digit (0-9), format it with a leading 0 (01-09 ).
M shows the month, represented by a number between 1 and 12 (including 1 and 12. If the month is a digit (1-9), it is displayed as a digit.
Note that if the "M" format specifier is used separately and there are no other custom format strings, it is interpreted as a standard month-day format specifier. If the "M" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
MM shows the month, represented by a number between 1 and 12 (including 1 and 12. If the month is a digit (1-9), format it with a leading 0 (01-09 ).
Mmm displays the abbreviation of the specified datetime month. If no specific valid format provider (a non-empty object that can implement the iformatprovider with the expected attribute) is provided, the abbreviatedmonthnames attribute of datetimeformat and the current culture associated with the current thread are used. Otherwise, use the abbreviatedmonthnames attribute from the specified format provider.
Mmmm displays the full name of the specified datetime month. If no specific valid format provider is provided (a non-empty object that can implement iformatprovider with expected attributes), use the monthnames attribute of datetimeformat and the current culture associated with the current thread. Otherwise, use the monthnames attribute from the specified format provider.
S displays the specified datetime seconds with a number ranging from 0 to 59. This number indicates the whole number of seconds since the last minute. If the second is a digit (0-9), it is displayed as only one digit.
Note that if the "S" format specifier is used separately and there are no other custom format strings, it is interpreted as a standard sortable date/time mode format specifier. If the "S" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
SS, SS (plus any number of additional "S" characters) display the specified datetime seconds with a number ranging from 0 to 59, this number of seconds indicates the whole number of seconds since the last minute. If the second is a digit (0-9), format it with a leading 0 (01-09 ).
T displays the first character of the. m./P. M. Indicator of the specified datetime. If no specific valid format provider is provided (a non-empty object that can implement iformatprovider with expected attributes), use the datetimeformat amdesignator (or pmdesignator) attribute and the current region associated with the current thread. Otherwise, use the amdesignator (or pmdesignator) Attribute from the specified iformatprovider. If the total number of hours for the specified datetime is less than 12, amdesignator is used. Otherwise, use pmdesignator.
Note that if the "T" format specifier is used separately and there are no other custom format strings, it is interpreted as a standard long-time format specifier. If the "T" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
TT, TT (plus any number of additional "T" characters) display the. m./P. M. Indicator of the specified datetime. If no specific valid format provider is provided (a non-empty object that can implement iformatprovider with expected attributes), use the datetimeformat amdesignator (or pmdesignator) attribute and the current region associated with the current thread. Otherwise, use the amdesignator (or pmdesignator) Attribute from the specified iformatprovider. If the total number of hours for the specified datetime is less than 12, amdesignator is used. Otherwise, use pmdesignator.
Y can be used to display the year of the specified datetime at most. Ignore the first two digits of the year. If the year is a digit (1-9), it is displayed as a digit.
Note that if the "y" format specifier is used separately and there are no other custom format strings, it is interpreted as a standard short date format specifier. If the "y" format specifier is passed together with other custom format specifiers or "%" characters, it is interpreted as a custom format specifier.
YY can display the year of the specified datetime with up to two digits. Ignore the first two digits of the year. If the year is a digit (1-9), format it with a leading 0 (01-09 ).
Yyyy displays the year of the specified datetime (including the epoch ). If the length of a year is less than four digits, add zero to the beginning to increase the length of the year to four digits.
Z only displays the time zone offset of the current time zone of the system in units of the hour. The total offset is displayed with a leading symbol (0 is displayed as "+ 0"), indicating the number of hours earlier than Greenwich Mean Time (+) or later than Greenwich Mean Time. The value range is-12 to + 13. If the offset is a single digit (0-9), it is displayed as a single digit with a proper leading symbol. The time zone is set in the form of + X or-X, where X is the hourly deviation from GMT. The displayed deviation is affected by the daylight saving time.
ZZ only displays the time zone offset of the current time zone of the system in units of the hour. The total offset is displayed with a leading or trailing sign (0 is displayed as "+ 00"), indicating the hours earlier than Greenwich Mean Time (+) or later than Greenwich Mean Time. The value range is-12 to + 13. If the offset is a single digit (0-9), format it to the front with 0 (01-09) and a proper leading symbol. The time zone is set in the form of + X or-X, where X is the hourly deviation from GMT. The displayed deviation is affected by the daylight saving time.
Zzz and ZZZ (plus any number of additional "Z" characters) display the time zone offset of the system's current time zone in units of hours and minutes. The offset is always displayed with a leading or trailing sign (0 is displayed as "+ 00:00"), indicating the hours earlier than Greenwich Mean Time (+) or later than Greenwich Mean Time. The value range is-to +. If the offset is a single digit (0-9), format it to the front with a leading 0 (01-09) with an appropriate leading symbol. The time zone is set in the form of + X or-X, where X is the hourly deviation from GMT. The displayed deviation is affected by the daylight saving time.
: Time separator.
/Date separator.
"String with quotation marks. Displays the text value of any string between two quotation marks after the escape character.
'String with quotation marks. Displays the text value of any string between two "'" characters.
% C indicates both standard and custom format specifiers, and displays the custom format mode associated with the format specifiers.
Note that if the format specifier is used separately as a single character, it will be interpreted as a standard format specifier. Only format specifiers that contain two or more characters are interpreted as custom format specifiers. The specifiers can be defined as both standard and custom format specifiers. to display the custom format of such specifiers, add the "%" symbol before the specifiers.
\ C contains any character, and the Escape Character displays the next character as text. In this context, the escape character cannot be used to create an escape sequence (for example, "\ n" indicates a line break ).
Other characters can be directly written to the output string as text.
 when a custom mode is passed to datetime. tostring, the mode must be at least two characters long. If only "D" is passed, the common language runtime interprets it as a standard format specifier because all single format specifiers are interpreted as standard format specifiers. If a single "H" is passed, an exception is thrown because there is no standard "H" format specifier. To format only a single custom format, add a space before or after the description. For example, the format string "H" is interpreted as a custom format string. 
the following example illustrates how to create a custom formatted string from datetime. This example assumes that the current region is American English (En-US ).
[Visual Basic]
dim mydate as new datetime (2000, 1, 1, 0, 0, 0)
dim mystring as string = mydate. tostring ("dddd-D-mmmm")
'in the U. s. english culture, mystring has the value:
'"Saturday-1-January ".
mystring = mydate. tostring ("yyyy gg")
'in the U. s. english cultures, mystring has the value: "2000. d. ".
[C #]
datetime mydate = new datetime (2000, 1, 1, 0, 0);
string mystring = mydate. tostring ("dddd-D-mmmm");
// in the U. s. english culture, mystring has the value:
// "Saturday-1-January ".
mystring = mydate. tostring ("yyyy gg");
// in the U. s. english cultures, mystring has the value: "2000. d. ".
For enumerative format strings, see
Formatting type | system. Enum | system. dayofweek Language
C #
 
Visual Basic
 
Show all
You can use the tostring method to create a New String object to represent the number, hexadecimal, or string value of enum. This method uses an enumerative formatted string to specify the value to be returned.
The following table lists the enumerated formatted strings and Their returned values. These format specifiers are case-insensitive.
Format String result
If possible, the enumerated items are displayed as string values. Otherwise, the integer of the current instance is displayed. If the flags attribute is set in the enumeration definition, concatenate the string values of each valid item and separate the values with commas. If the flags attribute is not set, the invalid value is displayed as a number.
If f or F is possible, the enumerated items are displayed as string values. If the value can be fully displayed as the sum of the enumerated items (even if the flags attribute is not provided), the string values of each valid item are concatenated and separated by commas. If the value cannot be completely determined by enumeration items, the value is formatted as an integer.
D or D shows the enumerated items as an integer in the shortest representation.
X or X displays the enumerated items as hexadecimal values. As needed, the value is represented with a leading zero to ensure that the length of the value is at least eight bits.
The following example defines an enumeration named colors, which contains three types: red, blue, and green.
[Visual Basic]
Public Enum colors
Red = 1
Blue = 2
Green = 3
End Enum
[C #]
Public Enum colors {Red = 1, Blue = 2, Green = 3}
After enumeration is defined, you can declare the instance as follows.
[Visual Basic]
Dim mycolors as colors = colors. Green
[C #]
Colors mycolors = colors. Green;
The following example uses the enumeration formatting method to assign the string, number, and hexadecimal representation of dayofweek to the string mystring. This Code creates a new instance named mydays for the dayofweek enumeration and assigns it Friday. Then, it uses the "g", "F", "D", and "X" format strings to assign different enumeration representations to mystring.
[Visual Basic]
Dim mydays as dayofweek = dayofweek. Friday
 
Dim mystring as string = mydays. tostring ("G ")
'In the U. S. English culture, mystring has the value: "Friday ".
 
Mystring = mydays. tostring ("F ")
'In the U. S. English culture, mystring has the value: "Friday ".
Mystring = mydays. tostring ("D ")
'In the U. S. English culture, mystring has the value: "5 ".
 
Mystring = mydays. tostring ("X ")
'In the U. S. English culture, mystring has the value: "00000005 ".
[C #]
Dayofweek mydays = dayofweek. Friday;
 
String mystring = mydays. tostring ("G ");
// In the U. S. English culture, mystring has the value: "Friday ".
 
Mystring = mydays. tostring ("F ");
// In the U. S. English culture, mystring has the value: "Friday ".
 
Mystring = mydays. tostring ("D ");
// In the U. S. English culture, mystring has the value: "5 ".
 
Mystring = mydays. tostring ("X ");
// In the U. S. English culture, mystring has the value: "00000005 ".
 
 
 
 

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.