Understanding String Formatting
Padding & Alignment
Composite formatting syntax supports three semantic for
- the padding length of each interpolation
- the direction of each padding for interpolation
- the format of each interpolation
What's padding? It fills out a string to a specified length using spaces. If the specified length is less than the length of the string, string remains the same. You can specify the direction to be left or right.
cs
// pad spaces on left
"123".PadLeft(20);
// 123
1
2
3
2
3
The second syntax in composite formatting is a optional integer for the interpolation:
- specify direction of padding by
-
(pad spaces on left) and pad on right by default - length of padding
cs
string.Format("{0,20}", 123);
// 123
string.Format("{0,-20}", 123);
// 123 ^ ends here
1
2
3
4
2
3
4
Format Convention
Numeric Format
G
for GeneralC
for Currency with decimal precision supportedB
for Binary numericD
for padding integers to specified trailing digit countE
for Exponential formate
for lowercase,1.23e+02
for example.
F
for Fixed-point numericN
for Numeric- formats to
ddd,ddd.ddd...
, trailing precision specifier is allowed
- formats to
P
for PercentageX
for heXadecimalx
for lowercase hexadecimal- trailing number after
X
orx
left pads to length with0
R
for Round-trip- supported for
Double
,Single
,Half
andBigInteger
only. - ensures the converted string represents the exact precision of the number.
- supported for