C# String Format Examples
Formatting strings in C# is not an easy task, as we usually forget format specifiers. In this article, we will note some of the important flags you can use.
Join the DZone community and get the full member experience.
Join For FreeMastering C# string format methods and remembering the various format specifiers can be tricky. Although the official String.Format documentation provides comprehensive details, it can be challenging to navigate quickly. In this article, we’ll simplify string formatting in C# by breaking down key concepts, common methods, and important format specifiers. From using string.Format
and StringBuilder
to leveraging the FormattableString
type, we’ll cover everything you need to know to make your code cleaner and more efficient.
What Is a Format String in C#?
A C# string format is a string that includes placeholders, defined using curly braces {}
, which are replaced with specified values at runtime using methods like string.Format
, Console.WriteLine
, or string interpolation ($
). The most common way to format strings is by using string.Format()
, which inserts the value of a variable, object, or expression into another string by replacing the format items with their string representation.
For example:
var msg = string.Format("There are {0} balls", 3);
Another way we can format a string is to use the StringBuilder.AppendFormat()
method:
decimal num = 34.53567325m;
var builder = new StringBuilder();
builder.AppendFormat("Format Decimal: {0:n2}", num);
And the third way to format a string is by using:
Console.WriteLine("There are {0} balls", 3);
In .NET 4.6, a new type called FormattableString
was introduced. It includes the format string that would typically be passed to string.Format (e.g. "Hello, {0}");
and the arguments needed for formatting. Importantly, this information is captured before the string is formatted, allowing you to adjust the formatting as needed — most commonly to use the invariant culture with the Invariant
static
method. For example:
FormattableString y = $"FormattableString: It is now {DateTime.UtcNow}";
Console.WriteLine(FormattableString.Invariant(y));
// Result: FormattableString: It is now 03/18/2021 10:40:45
Essentially, it provides greater control over string formatting, particularly for scenarios that require consistent formatting across different cultures.
Format Specifiers
Here is a quick reference to all the conversion specifiers supported.
Number Formats
Character | Description | Usage | Example |
---|---|---|---|
c | Currency | {0:c} | $ 55,674.74 |
e | Scientific | {0:e} | 5.567474e+004 |
f | Fixed point | {0:f} | 55674.74 |
g | General | {0:g} | 55674.73789621 |
n | Thousand Separator | {0:n} | 55,674.74 |
Custom Formats
Character | Description | Usage | Example |
---|---|---|---|
0 | Zero Placeholder | {0:00.00} | 55674.74 |
# | Digit Placeholder | {0:(#).##} | (55674).74 |
. | Decimal Point | {0:0.000} | 55674.738 |
, | Thousand Separator | {0:0,0} | 55,675 |
% | Percent | {0:0%} | 5567474% |
Date and Time Formats
Character | Description | Usage | Example |
---|---|---|---|
d | Short Date | {0:d} | 19-03-2021 |
D | Long Date | {0:D} | 19 March 2021 |
t | Short Time | {0:t} | 06:49:20 |
T | Long Time | {0:T} | 06:49:20 |
f or F | Long Date Time | {0:f} | 19 March 2021 06:49:00 |
g or G | Short Date Time | {0:g} | 19-03-2021 06:49:44 |
M | Short Date | {0:M} | March 19 |
r | RFC1123 Date Time String | {0:r} | Thu, 19 March 2021 06:49:22 GMT |
s | Sortable Date/Time | {0:s} | 2021-03-19T06:49:11 |
u | Universal Sortable Date | {0:u} | 2021-03-19 06:49:49Z |
U | Universal full date | {0:U} | 19 March 2021 00:18:55 |
Y | Year month pattern | {0:Y} | March, 2021 |
String Format Index
A string argument index is specified as an number in {}
and its positional.
string.Format("There are {0} balls and {1} rackets", 3, 5); // result: There are 3 balls and 5 rackets
Formatting Numeric Data
With {0:D}
we can format numbers in decimal format.
string.Format("Number: {0:N}", 157); // result: 157,00
We can also write like this:
string.Format("{0:D} {1,6:D}", 634, 868); // result: 634 868
The {0:D}
format item specifies the first item from the list of supplied objects that will be taken and formatted in decimal format. The {1,6:D}
format item takes the second item, format it also as a decimal and the string length will be 6 characters. Because the number has only three characters, it is right-aligned and padded with empty strings.
We can format a number in other notations, too, such as scientific, currency, percent, and hexadecimal:
string.Format("Scientific: {0:E}", 157); // result: 1.570000E+002
string.Format("Currency: {0:C}", 157); // result for US locale: $157.00
string.Format("Percent: {0:P}", 157); // result: 15,700.00%
string.Format("Hexadecimal: {0:X}", 157); // result: 9D
In addition, we can have format alignments, which represent a minimum number of characters to be written to the output. E.g., {0,10}
with right-align and for left-align, we need to specify a negative length, like {0,-10}
:
string.Format("{0,10}", 1);
// result: 1
String Cultures
String Format has also the following signature: public string Format(IFormatProvider, string, object)
Which means it accepts IFormatProvider
. It provides cultural info into the method and is normally implemented by a CultureInfo
class (e.g., CultureInfo.CurrentCulture
, CultureInfo.InvariantCulture
, etc.). The interface is a gateway for a function to get a set of culture-specific data from a culture. The three commonly available culture objects that an IFormatProvider
can be queried for are:
DateTimeFormatInfo
NumberFormatInfo
CultureInfo
For example:
DateTime dateValue = new DateTime(2021, 4, 16, 10, 40, 0);
var enUSCulture = new CultureInfo("en-US");
var itITCulture = new CultureInfo("it-IT");
Console.WriteLine("{0}: {1}", enUSCulture.Name, dateValue.ToString(enUSCulture));
// Result: en-US: 4/16/2021 10:40:00 PM
Console.WriteLine("{0}: {1}", itITCulture.Name, dateValue.ToString(itITCulture));
// Result: it-IT: 16/04/2021 10.40.00
String Interpolation — $
In C# 6 or later versions, String Interpolation is recommended. String interpolation is more flexible and more readable and can achieve the same results without composite formatting. The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions.
For example:
string name = "Mike";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation: Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Result: Both calls produce the same output that is similar to:
// Hello, Mike! Today is Tuesday, it's 10:40 now.
We can also use optional formatting component ({<interpolationExpression>[,<alignment>][:<formatString>]}
), alignment and formatString, which are part of Composite Format String. A composite format string and object list are used as arguments of methods that support the composite formatting feature. An optional alignment
component is a number indicating the preferred formatted field width, while the optional formatString
component is a format string that is appropriate for the type of object being formatted (custom or standard numeric format).
Console.WriteLine($"|{"Left",-7}|{"Right",7}|");
// Result: |Left | Right|
const int FieldWidthRightAligned = 20;
Console.WriteLine($"{Math.PI, FieldWidthRightAligned} - default formatting of the pi number");
// Result: 3.14159265358979 - default formatting of the pi number
Console.WriteLine($"{Math.PI, FieldWidthRightAligned:F3} - display only three decimal digits of the pi number");
// Result: 3.142 - display only three decimal digits of the pi number
Conclusion
Formatting strings in C# is a skill that can significantly enhance the clarity and efficiency of your code. Whether using string.Format
, StringBuilder.AppendFormat
, or the more modern string interpolation introduced in C# 6, each method provides powerful tools for crafting well-structured and readable output.
Additionally, understanding format specifiers, custom numeric and date/time formats, and culture-specific formatting allows developers to handle diverse data scenarios with precision. By mastering these techniques, you can make sure your applications maintain consistent and professional outputs across different contexts and use cases.
Opinions expressed by DZone contributors are their own.
Comments