C# String Format Examples - DZone Web Dev
Formatting strings in C# is not an easy task, as we usually forget format specifiers. In this text, we will note some of the important flags you can use.
If we take a look at the official C# String.Format documentation we can find all relevant information, but it's hard to navigate and find quickly what we need.
Here we will try to make this more clear.
String Formatting
The most common way how we format strings is by using string.Format(). In C#, the string Format method is used to insert the value of the variable or an object or expression into another string. By using the string.Format method, we can replace the format items in the specified string with the string representation of specified objects.
var msg = string.Format("There are {0} balls", 3);
Other way how 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 string is by using:
Console.WriteLine("There are {0} balls", 3);
In .NET 4.6 is added a new type called FormattableString, which consists of the format string which would be passed to string.Format (e.g. "Hello, {0}"); and the arguments that would be passed in order to format it. Crucially, this information is captured before formatting. This allows you to adjust the formatting appropriately — most commonly to perform it in the invariant culture, often 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:45Format 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 racketsFormatting Numeric Data
With {0:D} we can format numbers in decimal format.
string.Format("Number: {0:N}", 157); // result: 157,00We can also write like this:
string.Format("{0:D} {1,6:D}", 634, 868); // result: 634 868The {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: 9DIn 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: 1String Cultures
String Format has also the following signature: public string Format(IFormatProvider, string, object)
Which means it accept 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.00String 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 numberTừ khóa » C# 0 Vs 0m
-
Using 0M Instead Of 0 For Decimal Values? - Stack Overflow
-
Why Is There A Difference Between Decimal 0 And 0.0?
-
What Does It Means? - C# / C Sharp - Bytes Developer Community
-
Floating-point Numeric Types - C# Reference - Microsoft Docs
-
Decimal.Zero Field (System) - Microsoft Docs
-
What Is Decimal.Zero In C#?
-
High-precision Calculation In C# With Decimal - ZetCode
-
C# Decimal Examples - Dot Net Perls
-
見落としがちな不具合[2013/06/18] - 猫の気ままなC#日記
-
Decimal Values And Trailing Zeroes - Blackwasp UK
-
[PDF] 01123245 7489 9 93245 1 - ILO
-
The Null-Coalescing Operator - Ben Gribaudo