The String.Format() method is used to create a formatted string by replacing placeholders with values from variables, objects, or expressions. It belongs to the System.String class and supports formatting numbers, dates, currencies, and other data types.
- Uses indexed placeholders such as {0}, {1}, and {2} to insert values.
- Supports custom formatting for numbers, dates, and text alignment.
- Allows culture-specific formatting using an IFormatProvider.
Syntax of String.Format()
string.Format(string format, params object[] args);
Parameters:
- format: A composite format string containing placeholders.
- args: The values used to replace the placeholders.
Return Value: Returns a new formatted string without modifying the original string.
using System;
class Geeks{
public static void Main(String[] args){
String s = "Geeks";
// Using the String.Format Method
String res = String.Format("Hello, {0}!", s);
// Displaying the String
Console.WriteLine(res);
}
}
Output
Hello, Geeks!
Explanation: The placeholder {0} is replaced by the value of name. Placeholder indexing starts at 0, so {1} refers to the second argument, and so on.
How String.Format() Works
The String.Format() method uses composite formatting to insert values into a predefined string.
Placeholder Syntax:
{index[,alignment][:formatString]}
Component | Description |
|---|---|
index | Zero-based position of the argument |
alignment | Optional field width; positive values right-align and negative values left-align |
formatString | Optional format specifier for numbers, dates, or other supported values |
For example, {0:F2} formats the first argument as a fixed-point number with two decimal places, while {1,-10} left-aligns the second argument within a field of at least 10 characters.
String.Format() Method Overloads
The String.Format() method provides several overloads to format one or more values, including overloads that accept an IFormatProvider.
Method Signature | Description |
|---|---|
Format(string, object) | Formats one value. |
Format(string, object, object) | Formats two values. |
Format(string, object, object, object) | Formats three values. |
Format(string, params object[]) | Formats multiple values. |
Format(IFormatProvider, string, object) | Formats one value using a specified provider. |
Format(IFormatProvider, string, object, object) | Formats two values using a specified provider. |
Format(IFormatProvider, string, object, object, object) | Formats three values using a specified provider. |
Format(IFormatProvider, string, params object[]) | Formats multiple values using a specified provider. |
Modern .NET versions also provide generic formatting overloads. The table above covers the commonly used object-based overloads.
Examples of String.Format()
Example 1: Formatting Multiple Values
The following example inserts multiple values into a formatted string.
using System;
class Geeks{
static void Main(){
string name = "Rahul";
int age = 25;
string result = string.Format("Name: {0}, Age: {1}",
name, age);
Console.WriteLine(result);
}
}
Output
Name: Rahul, Age: 25
Explanation: {0} is replaced with name, and {1} is replaced with age.
Example 2: Formatting Numbers
The following example uses the F2 format specifier to display a decimal value with two digits after the decimal point.
using System;
using System.Globalization;
class Geeks{
static void Main(){
double price = 123.456;
string result
= string.Format(CultureInfo.InvariantCulture,
"Price: {0:F2}", price);
Console.WriteLine(result);
}
}
Output
Price: 123.46
Explanation: {0:F2} rounds the displayed value to two decimal places. InvariantCulture ensures that the decimal separator is a period.
Example 3: Formatting Dates
The following example formats a DateTime value using the specified culture.
using System;
using System.Globalization;
class Geeks{
static void Main(){
DateTime date = new DateTime(2025, 3, 16);
CultureInfo culture = new CultureInfo("en-US");
string result
= string.Format(culture, "Date: {0:D}", date);
Console.WriteLine(result);
}
}
Output
Date: Sunday, March 16, 2025
Explanation: The D format specifier displays the long date format, while en-US determines the date's culture-specific representation.
Example 4: Aligning Text
The following example uses alignment values to format text.
using System;
class Geeks{
static void Main(){
Console.WriteLine(
string.Format("|{0,-10}|{1,10}|", "Name", "Marks"));
Console.WriteLine(
string.Format("|{0,-10}|{1,10}|", "Rahul", 95));
}
}
Output
|Name | Marks| |Rahul | 95|
Explanation: {0,-10} left-aligns text within a 10-character field, while {1,10} right-aligns the value within a 10-character field.
Common Format Specifiers
The following format specifiers can be used with String.Format() when supported by the argument's data type.
Specifier | Purpose | Example |
|---|---|---|
D | Decimal integer | {0:D5} → 00025 |
F2 | Two decimal places | {0:F2} → 12.35 |
N2 | Number with grouping separators | {0:N2} → 1,234.50 |
C | Currency formatting | {0:C} |
P | Percentage formatting | {0:P0} → 25% |
d | Short date | {0:d} |
D | Long date | {0:D} |
X | Hexadecimal integer | {0:X} → FF |
The results depend on the value's type and, for some specifiers, the selected culture.
Advantages of String.Format()
- Readable Formatting: Combines text and values using indexed placeholders.
- Flexible Output: Supports numeric, date, currency, and alignment formatting.
- Reusable Templates: The same format string can be reused with different values.
- Culture Support: Allows culture-specific formatting through IFormatProvider.
Limitations of String.Format()
- Runtime Errors: Invalid placeholders or missing arguments can cause a FormatException.
- Index Management: Managing numbered placeholders can become difficult in lengthy strings.
- Additional Allocation: Produces a new string rather than modifying an existing one.
- Readability: String interpolation is often easier to read for simple formatting expressions.