C# String Formatting

Time and again I’m forgetting about C# string formatting syntax. The MS pages about it are bad.
But here is a page with a lot of number string formatting examples and at the bottom a little testing tool. Quite valuable.

Some examples I wanted to mention here:

| double d= |    a=     | d.ToString(a) | remark 
|-----------|-----------|---------------|--------
| 1234.57   | "0"       | 1235          | rounded  
| 1234.57   | "0.0"     | 1234.6        | rounded  
| 1234      | "0.0"     | 1234.0        | .0: show digit always 
| 1234.57   | "0.#"     | 1234.6        | .#: show digit only if needed 
| 1234.57   | "0.##"    | 1234.57       |
| 1234.57   | "0.###"   | 1234.57       |
| 1234      | "0.#"     | 1234          | 
| 1234.567  | "F1"      | 1234.6        | F: float with one decimal
| 1234.567  | "F"       | 1234.57       | F: float with two decimals 
| 1234.567  | "F3"      | 1234.567      | F: float with three decimals 
|    1.23   | "##.##"   | 1.23          | #.: show digit only if needed 
|    0.23   | "##.##"   | .23           |
|    0.23   | "#0.##"   | 0.23          |
|    0.23   | "00.##"   | 00.23         |
|    0.23   | ",5#0.##" |  0.23         | Probably does not work with 
|      d.ToString(a), but does work with string.Format or  
|      string interpolation.

| int d= |    a=        | d.ToString(a) | remark 
|--------|--------------|---------------|--------
|   12   | "0"          | 12            |   
|   12   | "00"         | 12            | 
|   12   | "000"        | 012           | 
|   12   | "+00;X00"    | +12           | first for > 0 
|   12   | "X"          | C             |  
|   12   | "x4"         | 000c          |
|   -12  | "+00;X00"    | X12           | second for < 0  
|   0    | "+00;X00"    | +0            | first for == 0
|   0    | "+00;X00;AQ" | AQ            | third for == 0, if existing

String interpolation $"{d}" can be formatted with all the same format markers like this: $"{d:0.##}".

Here is a page with a lot of DateTime string formatting examples and at the bottom a little testing tool. Quite valuable.

Some examples I wanted to mention here:

| DateTime d=         |    a=                  | d.ToString(a)  
|---------------------|------------------------|------------------
| 2020-05-19 13:47:27 | "yy-MM-dd HH:mm:ss"    | 20-05-19 13:47:27 
| 2020-05-19 13:47:27 | "yyyy-MM-dd HH:mm"     | 2020-05-19 13:47 
| 2020-05-19 13:47:27 | "yyyyMMddTHHmm"        | 20200519T1347 

| DateTime d=         | c = Culture.       | d.ToString(c)  
|                     | GetCultureInfo(..) |
|---------------------|--------------------|----------------------
| 2021-05-19 13:47:27 |        "DE"        | 19.05.2021 13:47:27
| 2021-05-19 13:47:27 |        "PL"        | 19.05.2021 13:47:27
| 2021-05-19 13:47:27 |        "RU"        | 19.05.2021 13:47:27
| 2021-05-19 13:47:27 |        "en-GB"     | 19/05/2021 13:47:27
| 2021-05-19 13:47:27 |        "en-US"     | 5/19/2021 1:47:27 PM