C# string formatting

Posted on Updated on

Miscellaneous reminders on how to use string.Format

1. Padding a string with fixed size, for example a string field that is a fixed width of 30 characters.

string.Format( "{0,50}", "field with less than 50 characters"
// {0,50}  --> displays string value right justified
// {0.-50} --> displays string value left justified

2. Variable width string formatting

int len = 20;
string fmt = string.Format( "{{0,{{0}}}", len );
string.Format( fmt, "field with less than 50 characters" );

3. Comma separators for numeric values.

string.Format( "{0:N0}", 123456 );  // 12,3456

4. string format for doubles

Leave a Reply

Your email address will not be published. Required fields are marked *