|
| 1 | +# Understanding String Formatting |
| 2 | + |
| 3 | +## Padding & Alignment |
| 4 | + |
| 5 | +Composite formatting syntax supports three semantic for |
| 6 | + |
| 7 | +- the padding length of each interpolation |
| 8 | +- the direction of each padding for interpolation |
| 9 | +- the format of each interpolation |
| 10 | + |
| 11 | +What's padding? It fills out a string to a specified length using spaces. |
| 12 | +If the specified length is less than the length of the string, string remains the same. |
| 13 | +You can specify the direction to be left or right. |
| 14 | + |
| 15 | +```cs |
| 16 | +// pad spaces on left |
| 17 | +"123".PadLeft(20); |
| 18 | +// 123 |
| 19 | +``` |
| 20 | + |
| 21 | +The second syntax in composite formatting is a optional integer for the interpolation: |
| 22 | + |
| 23 | +- specify direction of padding by `-`(pad spaces on left) and pad on right by default |
| 24 | +- length of padding |
| 25 | + |
| 26 | +```cs |
| 27 | +string.Format("{0,20}", 123); |
| 28 | +// 123 |
| 29 | +string.Format("{0,-20}", 123); |
| 30 | +// 123 ^ ends here |
| 31 | +``` |
| 32 | + |
| 33 | +## Format Convention |
| 34 | + |
| 35 | +### Numeric Format |
| 36 | + |
| 37 | +- `G` for **G**eneral |
| 38 | +- `C` for **C**urrency with decimal precision supported |
| 39 | +- `B` for **B**inary numeric |
| 40 | +- `D` for padding **integers** to specified trailing digit count |
| 41 | +- `E` for **E**xponential format |
| 42 | + - `e` for lowercase, `1.23e+02` for example. |
| 43 | +- `F` for **F**ixed-point numeric |
| 44 | +- `N` for **N**umeric |
| 45 | + - formats to `ddd,ddd.ddd...`, trailing precision specifier is allowed |
| 46 | +- `P` for **P**ercentage |
| 47 | +- `X` for he**X**adecimal |
| 48 | + - `x` for lowercase hexadecimal |
| 49 | + - trailing number after `X` or `x` left pads to length with `0` |
| 50 | +- `R` for **R**ound-trip |
| 51 | + - supported for `Double`, `Single`, `Half` and `BigInteger` only. |
| 52 | + - ensures the converted string represents the exact precision of the number. |
| 53 | + |
| 54 | + |
| 55 | +## `ToString` & `IFormattable` |
0 commit comments