DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Formatting Strings in Java: String.format() Method
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Zero to AI Hero, Part 2: Understanding Plugins in Semantic Kernel, A Deep Dive With Examples

Trending

  • Infrastructure as Code (IaC) Beyond the Basics
  • A Modern Stack for Building Scalable Systems
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  • Transforming AI-Driven Data Analytics with DeepSeek: A New Era of Intelligent Insights
  1. DZone
  2. Coding
  3. Languages
  4. C# String Format Examples

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.

By 
Milan Milanovic user avatar
Milan Milanovic
DZone Core CORE ·
Updated Dec. 04, 24 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
233.2K Views

Join the DZone community and get the full member experience.

Join For Free

Mastering 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:

C#
 
var msg = string.Format("There are {0} balls", 3);


Another way we can format a string is to use the StringBuilder.AppendFormat() method:

C#
 
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:

C#
 
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:

C#
 
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 a number in {} and is positional.

C#
 
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.

C#
 
string.Format("Number: {0:N}", 157); // result: 157,00


We can also write like this:

C#
 
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, formats 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:

C#
 
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}:

C#
 
string.Format("{0,10}", 1); 
// result:          1


String Cultures

String Format also has 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:

C#
 
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:

C#
 
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).

C#
 
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.

Strings csharp Interpolation C# (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Writing DTOs With Java8, Lombok, and Java14+
  • Formatting Strings in Java: String.format() Method
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel
  • Zero to AI Hero, Part 2: Understanding Plugins in Semantic Kernel, A Deep Dive With Examples

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!