Formatting data output method

Source: Internet
Author: User

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 ();}}}

 

Related Article

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.