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  | "F"       | 1234.57       | F: float with two 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.


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-HH-dd HH:mm:ss"    | 20-05-19 13:47:27 
| 2020-05-19 13:47:27 | "yyyy-HH-dd HH:mm"     | 2020-05-19 13:47 
| 2020-05-19 13:47:27 | "yyyHHddTHHmm"         | 20200519T1347 

Leave a Reply

Your email address will not be published.