We usually use the formatting data output method provided by the Console class. Is there any other method in C # That can be used? The answer is yes. The formatting method of the String class can also have the same function. The String class provides a powerful Format () method for formatting strings. Its syntax is similar to WriteLine.
Format () Syntax:
String str = string. Format ("formatted string", parameter list );
A simple example:
String str = string. Format ("{0} + {1} = {2}", 1, 2, 1 + 2 );
Console. WriteLine (str );
Output result:
1 + 2 = 3
Among them, "{0} + {1} = {2}" is the format string, {0}, {1}, {2} is the placeholder.
In addition to the above usage, the string. Format () method also provides the function of formatting numeric values. The specific usage is shown in the table:
Formatted numeric character description sample 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 regular string. Format ("{0: G}", 2) 2
String. Format ("{0: N}", 25000) 25,000.00
X hexadecimal string. Format ("{0: X000}", 12) C
P % string. Format ("{0: P}", 12.34) 1234.00%
Example:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace FormatTest {class Program {static void Main (string [] args) {string str = string. empty; Console. writeLine ("standard digital format"); str = string. format ("(C) Currency: {0: C} \ n" + "(D) Decimal: {0: D} \ n" + "(G) General: {1: G} \ n "+" (p) Percent: {1: P} \ n "+" (X) Hexadecimal: {0: X} \ n ", -12345,-123.4567f); Console. writeLine (str); Console. readLine ();}}}