Implementation code for C # format Strings _c# Tutorial

Source: Internet
Author: User
Tags datetime numeric iso 8601 local time string format time interval

1 Preface

If you are familiar with the WTL or CString standard of the Cstring,windows Template Library (Template) of Microsoft Foundation Classes (MFC) Library (STL) String class, then you must be familiar with the String.Format method. This method is often used in C # to format strings, such as the following:

int x =;
Decimal y = 3.57m;
String h = String.Format ("Item {0} sells at {1:c}", X, y);
Console.WriteLine (h);

On my machine, I can get the following output:

Item sells at¥3.57

Maybe the output on your machine is not the same as this one. This is normal, and this article will explain the problem later.

In our daily use, more is the use of the Console.WriteLine method to output a string. In fact, String.Format and Console.WriteLine have a lot in common. Two methods have many overloaded formats and take an array of objects with no fixed arguments as the last argument. The following two statements produce the same output.

Console.WriteLine ("Hello {0} {1} {2} {3} {4} {5} {6} {7} {8}", 123, 45.67, True, ' Q ', 4, 5, 6, 7, ' 8 ');
string u = String.Format ("Hello {0} {1} {2} {3} {4} {5} {6} {7} {8}"), 123, 45.67, True, ' Q ', 4, 5, 6, 7, ' 8 ');
Console.WriteLine (u);

The output is as follows:

Hello 123 45.67 True Q 4 5 6 7 8
Hello 123 45.67 True Q 4 5 6 7 8

2 string format

String.Format and WriteLine All follow the same formatting rules. The formatted format is as follows: "{N [, M] [: formatstring]}", Arg1, ... argn, in this format:

1) n is an integer starting at 0, representing the number of parameters to format

2 m is an optional integer that represents the width of the formatted parameter, if M is a negative number, the formatted value is left-aligned, and if M is a positive number, the formatted value is right-aligned

3) formatstring is another optional parameter that represents the format code

Argn represents the expression to be formatted, and n is the corresponding.

If the argn is a null value, replace it with an empty string. If there is no formatstring, then the parameter n corresponds to the ToString method to format. The following statement produces the same output:

public class Testconsoleapp
{public
 static void Main (string[] args)
 {
  Console.WriteLine (123);
  Console.WriteLine ("{0}", 123);
  Console.WriteLine ("{0:d3}", 123);
 }

The output is:

123
123
123

You can also get the same output through String.Format.

string s = String. Format ("123");
String t = String. Format ("{0}", 123);
string u = String. Format ("{0:d3}", 123);
Console.WriteLine (s);
Console.WriteLine (t);
Console.WriteLine (u);

Therefore, the following conclusions are drawn:

(, M) determines the width and alignment of the formatted string

(: formatstring) determines how data is formatted, such as a currency symbol, a scientific notation, or a 16-way system. Just like the following:

Console.WriteLine ("{0,5} {1,5}", 123, 456);  Right-aligned
Console.WriteLine ("{0,-5} {1,-5}", 123, 456);//left-aligned

Output is

123 456
123 456

You can also merge these expressions, put a comma first, and then place a colon. Just like this:

Console.WriteLine ("{0,-10:d6} {1,-10:d6}", 123, 456);

The output is:

000123 000456

We can use this formatting feature to align our output.

Console.WriteLine ("\n{0,-10}{1,-3}", "Name", "Salary");
Console.WriteLine ("----------------");
Console.WriteLine ("{0,-10}{1,6}", "Bill", 123456);
Console.WriteLine ("{0,-10}{1,6}", "Polly", 7890);

The output is:

Name Salary
----------------
Bill 123456
Polly 7890

3 Formatting identifiers

Standard mathematical format strings are used to return strings that are normally used. They are usually in a format such as X0. X is the format identifier, and 0 is the precision identifier. There are 9 types of format identifiers, which represent most commonly used number formats. As shown in the following table:

Letters Meaning
C or C Currency Currency format
D or D Decimal decimal format (decimal integer, not and. The decimal data type of net is confused)
E or E Exponent index Format
F or F Fixed point invariant precision format
G or G General format
N or N Divide thousands by commas, like 1234 will be turned into 1,234.
P or P Percentage percent sign format
R or R Round-trip rounding (for floating-point numbers only) ensures that a number is converted to a string and can then be reversed back to the same number
X or X Hex 16 binary format

If we use the following expression, let's see what happens

public class Formatspecapp
{public
 static void Main (string[] args)
 {
  int i = 123456;
  Console.WriteLine ("{0:c}", i); ¥123,456.00
  Console.WriteLine ("{0:d}", i);//123456
  Console.WriteLine ("{0:e}", i);//1.234560E+005
  Console.WriteLine ("{0:f}", i); 123456.00
  Console.WriteLine ("{0:g}", i);//123456
  Console.WriteLine ("{0:n}", i);//123,456.00
  Console.WriteLine ("{0:p}", i); 12,345,600.00%
  Console.WriteLine ("{0:x}", i);//1E240
 }
}

The Precision control ID controls the number of valid digits or the number of decimal digits.

Console.WriteLine ("{0:c5}", i); ¥123,456.00
Console.WriteLine ("{0:d5}", i);//123456
Console.WriteLine ("{0:e5}", i);//1.23456E+005
Console.WriteLine ("{0:f5}", i); 123456.00000
Console.WriteLine ("{0:g5}", i);//1.23456E5
Console.WriteLine ("{0:n5}", i);//123,456.00000
Console.WriteLine ("{0:P5}", i);//12,345,600.00000%
Console.WriteLine ("{0:x5}", i); 1E240

The R (round) format is only valid for floating-point numbers. This value is first formatted in a common format. For a double-precision number of 15-bit precision, there are 7-bit precision for single precision. If the value can be parsed correctly back to the original number, it will be formatted with a common format character. If you cannot parse back, then you will use 17-bit precision to format the double-precision number, with 9-bit precision to format the single-precision number. Although we can add a number of digits to a valid number after the rounded identifier, it is ignored.

Double d = 1.2345678901234567890;
Console.WriteLine ("Floating-point:\t{0:f16}", D); 1.2345678901234600
Console.WriteLine ("Roundtrip:\t{0:r16}", d);  1.2345678901234567

If the standard format identifier is not enough for you. You can use a graphical format string to create custom string output. Graphical formatting uses placeholders to represent the minimum digits.

The maximum number of digits, the positioning symbol, the appearance of the minus sign, and the appearance of other numeric symbols. As shown in the following table

The
symbol name meaning
0 0 placeholder with 0 fill insufficient digits
# Digit placeholder replaces the actual number of digits with #
. decimal point  
, Thousands separator comma for thousands, such as dividing 1000 into 1,000
% percent sign display a percentile identification
e+0
E-0
e+0
e-0
exponent symbol format output with exponential notation
\ single-minded characters is used for formatting sequences in traditional formats, such as "\ n" (New line)
' abc '
ABC
constant string   display the string inside single or double quotes
; Zone separator   if numbers are formatted as integers, negative numbers, or 0, delimited by;
,. scale symbol number divided by 1000

Look at the following example:

Double i = 123456.42;
   Console.WriteLine (); Console.WriteLine ("{0:000000.00}", i); 123456.42 Console.WriteLine ("{0:00.00000000e+0}", i);   12.34564200e+4 Console.WriteLine ("{0:0,.}", i);    123 Console.WriteLine ("{0: #0.}", i);  123456.420 Console.WriteLine ("{0: #0; (#0)}", i); 123456.420 Console.WriteLine ("{0: #0; (#0); <zero>}", i);  123456.420 Console.WriteLine ("{0:#%}", i);
   12345642% i =-123456.42;
   Console.WriteLine (); Console.WriteLine ("{0:000000.00}", i); -123456.42 Console.WriteLine ("{0:00.00000000e+0}", i);   -12.34564200e+4 Console.WriteLine ("{0:0,.}", i);    -123 Console.WriteLine ("{0: #0.}", i);  -123456.420 Console.WriteLine ("{0: #0; (#0)}", i); (123456.420) Console.WriteLine ("{0: #0;(#0); <zero>}", i);    (123456) Console.WriteLine ("{0:#%}", i);
   -12345642% i = 0;
   Console.WriteLine ();   Console.WriteLine ("{0:0,.}", i); 0 Console.WriteLine ("{0: #0} ", i);  0 Console.WriteLine ("{0: #0;(#0)}", i); 0 Console.WriteLine ("{0: #0;(#0); <zero>}", i);    <zero> Console.WriteLine ("{0:#%}", i); // %

4 parsing of numeric strings

All underlying types have the ToString method, which is inherited from the object type. All numeric types have a parse method, which uses a string as a parameter and returns an equal number. Like what

public class Numparsingapp
{public
 static void Main (string[] args)
 {
  int i = Int. Parse ("12345");
  Console.WriteLine ("I = {0}", i);

  Int J = Int32.Parse ("12345");
  Console.WriteLine ("J = {0}", j);

  Double d = double.parse ("1.2345E+6");
  Console.WriteLine ("D = {0:f}", d);

  string s = i.tostring ();
  Console.WriteLine ("s = {0}", s);
 }
}

Output is as follows

i = 12345
j = 12345
D = 1234500.00
s = 12345

By default, some non-numeric characters can exist. such as the opening and closing of the blank. Commas and decimal points, plus and minus signs, so the following parse statement is the same

String t = " -1,234,567.890";
Double g = Double. Parse (t);  Do the same thing as the following code
double g = Double. Parse (t, 
 numberstyles.allowleadingsign | 
 Numberstyles.allowdecimalpoint |
 NumberStyles.AllowThousands |
 Numberstyles.allowleadingwhite | 
 Numberstyles.allowtrailingwhite);
Console.WriteLine ("G = {0:f}", g);

The output is like this

g =-1234567.89

Note that if you want to use NumberStyles, add a reference to System.Globalization, and then you can use a combination of different numberstyles or any of them. If you want to be compatible with the currency symbol, you need to use the overloaded parse method, which takes a NumberFormatInfo object as an argument, and then you can set the NumberFormatInfo CurrencySymbol property to invoke the Parse method. Like what:

string u = "¥-1,234,567.890";
NumberFormatInfo ni = new NumberFormatInfo ();
Ni. CurrencySymbol = "¥";
Double h = double.parse (U, Numberstyles.any, ni);
Console.WriteLine ("H = {0:f}", h);

The code above has the following output

H =-1234567.89

In addition to NumberFormatInfo, you can also use the CultureInfo class. CultureInfo represents a particular culture, including the name of the culture, the way it is written, the format of the calendar. The operation of a particular culture is very common, such as formatting dates and sorting. Cultural naming follows the RFC1766 standard, using the < language code 2>-< country/region code 2>, where the < language code 2> is two lowercase letters from the iso639-1;< country/region code 2> is two uppercase letters, they come from ISO3166. For example, American English is "en-us". British English is "EN-GB". Trinidad And Tobago English is "En-tt". For example, we can create a CultureInfo object in American English and convert numbers to strings based on this culture.

int k = 12345;
CultureInfo we = new CultureInfo ("en-us");
String v = k.tostring ("C", US);
Console.WriteLine (v);

The output is:

$12,345.00

Note that we used the overloaded ToString method, which takes the first formatted string as the first argument, and a CultureInfo object (the IFormatProvider object) as the second argument. Here is a second example, for the Danes:

CultureInfo DK = new CultureInfo ("DA-DK");
string w = k.tostring ("C", DK);
Console.WriteLine (w);

The output is:

KR 12.345,00

5 Strings and dates

A Date object has an attribute called ticks. It stores a time interval of 100 nanoseconds since the beginning of the January 1 of the year of 1, 12 o'clock in the morning. For example, the ticks value equals 31241376000000000L for the time of 100, Friday, January 1, 12 o'clock in the morning. Ticks always increments at 100 nanosecond intervals.

The value of datetime is represented by the standard or custom method stored in the DateTimeFormatInfo instance. In order to modify the way a date is displayed, the DateTimeFormatInfo instance must be writable so that we can write the custom format and deposit it in the attribute

Using System.Globalization;

public class Datesapp
{public
 static void Main (string[] args)
 {
  DateTime dt = DateTime.Now;
  Console.WriteLine (DT);
  Console.WriteLine ("date = {0}, time = {1}\n",
   dt.) Date, dt. TimeOfDay);
 }

The code produces the following output

23/06/2001 17:55:10
Date = 23/06/2001 00:00:00, time = 17:55:10.3839296

The following table lists the standard format strings and the associated DateTimeFormatInfo properties

D
D Mm/dd/yyyy ShortDatePattern (short date mode)
D Dddd,mmmm dd,yyyy Longdatepattern (long date mode)
F Dddd,mmmm dd,yyyy hh:mm Full date and times (long date and short) (all date and time mode)
F Dddd,mmmm dd,yyyy HH:mm:ss Fulldatetimepattern (long date and long time)
G MM/DD/YYYY hh:mm General (shorter date and short time) (common mode, short dates and shorter times)
G MM/DD/YYYY HH:mm:ss General (shorter date and long time) (common mode, short and long)
Mm MMMM DD Monthdaypattern (Month-day mode)
R,r Ddd,dd MMM yyyy,hh ': ' mm ': ' SS ' GMT ' Rfc1123pattern (RFC1123 mode)
S YYYY-MM-DD HH:mm:ss Sortabledatetimepattern (conforms to ISO 8601) using the local time (sortable mode with native times)
T hh:mm Shorttimepattern (short time mode)
T HH:mm:ss Longtimepattern (long time mode)
U YYYY-MM-DD HH:mm:ss Universalsortable-datetimepattern (conforms to ISO 8601) using Universal Time (Universal sortable mode)
U Dddd,mmmm Dd,yyyy,hh:mm:ss Universalsortable-datetimepattern (Universal sortable mode)
Y,y Mmmm,yyyy Yearmonthpattern (month and year pattern)

The Datetimeformatinfo.invariantinfo property gets the default read-only DateTimeFormatInfo instance, which is culturally independent. You can create a custom pattern. Note that Invariantinfo is not necessarily the same as the local format. Invariant equals American format. Also, if the second argument you pass to the Datetime.format method is Null,datetimeformatinfo will be the default currentinfo. Like what

Console.WriteLine (dt. ToString ("D", Dtfi));
Console.WriteLine (dt. ToString ("D", null));
Console.WriteLine ();

Output is

06/23/2001
23/06/2001

Choose between Invariantinfo and CurrentInfo.

DateTimeFormatInfo Dtfi;
Console.Write ("[I]nvariant or [C]urrent Info?:");
if (console.read () = = ' I ')
 Dtfi = Datetimeformatinfo.invariantinfo;
else
 Dtfi = datetimeformatinfo.currentinfo;
DateTimeFormatInfo Dtfi = datetimeformatinfo.invariantinfo;
Console.WriteLine (dt. ToString ("D", Dtfi));
Console.WriteLine (dt. ToString ("F", Dtfi));
Console.WriteLine (dt. ToString ("F", Dtfi));
Console.WriteLine (dt. ToString ("G", Dtfi));
Console.WriteLine (dt. ToString ("G", Dtfi));
Console.WriteLine (dt. ToString ("M", Dtfi));
Console.WriteLine (dt. ToString ("R", Dtfi));
Console.WriteLine (dt. ToString ("s", Dtfi));
Console.WriteLine (dt. ToString ("T", Dtfi));
Console.WriteLine (dt. ToString ("T", Dtfi));
Console.WriteLine (dt. ToString ("U", Dtfi));
Console.WriteLine (dt. ToString ("U", Dtfi));
Console.WriteLine (dt. ToString ("D", Dtfi));
Console.WriteLine (dt. ToString ("Y", Dtfi));
Console.WriteLine (dt. ToString ("Dd-mmm-yy", Dtfi));

Output is

[I]nvariant or [C]urrent Info?: I
01/03/2002
03/01/2002

Thursday, January 2002
Thursday, January 2002 12:55
Thursday, January 2002 12:55:03
01/03/2002 12:55
01/03/2002 12:55:03
January 03
Thu, 2002 12:55:03 GMT
2002-01-03t12:55:03
12:55
12:55:03
2002-01-03 12:55:03z
Thursday, January 2002 12:55:03
01/03/2002
2002 January
03-jan-02


[I]nvariant or [C]urrent Info?: C
03/01/2002
03/01/2002

2002 January
2002 12:55 January
2002 12:55:47 January
03/01/2002 12:55
03/01/2002 12:55:47
January
Thu, 2002 12:55:47 GMT
2002-01-03t12:55:47
12:55
12:55:47
2002-01-03 12:55:47z
2002 12:55:47 January
03/01/2002
January 2002
03-jan-02

/******************************************************************************************
* "Author" : Flyingbread
* "Date": January 18, 2007
* "Notice":
* 1, this article is the original technical article, the starting blog Garden personal site (http://flyingbread.cnblogs.com/), Please indicate the author and the source of the quotation.
* 2, this article must be reproduced and cited in full text, any organization and individual is not authorized to modify any content, and not authorized to be used in business.
* 3, this declaration is part of the article, reprint and reference must be included in the original.
******************************************************************************************/

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.