csharp-formato-strings

How to Format Strings in C#

  • 4 min

Formatting a string means building a string from text and values with a specific representation.

In C# we have several ways to do this, from concatenation to interpolation or String.Format. The choice depends mainly on the readability we need and the type of format we want to apply.

String Concatenation

The most direct way is to concatenate several strings with the + operator:

string nombre = "Juan";
int edad = 25;
string mensaje = "Hola, mi nombre es " + nombre + " y tengo " + edad + " años.";

Console.WriteLine(mensaje);
Copied!
Hola, mi nombre es Juan y tengo 25 años.
Copied!

This approach works well in simple cases, although it loses readability when many values are involved or when we need to apply different formats.

Using String.Format

String.Format inserts values into a string using numbered placeholders:

string resultado = string.Format("Texto con valor: {0}", valor);
Copied!

The number in {0} is a format index. It is replaced by the argument occupying that position after the format string.

string nombre = "Ana";
int edad = 30;
string mensaje = string.Format(
    "Hola, mi nombre es {0} y tengo {1} años.",
    nombre,
    edad);

Console.WriteLine(mensaje);
Copied!
Hola, mi nombre es Ana y tengo 30 años.
Copied!

We can also add a specifier after a colon. For example, F2 displays a floating-point number with two decimal places:

double precio = 15.6789;
string mensaje = string.Format("El precio es: {0:F2}", precio);

Console.WriteLine(mensaje);
Copied!
El precio es: 15.68
Copied!

String Interpolation

String interpolation allows inserting variables or expressions directly within curly braces. To do this, we add $ before the string:

string nombre = "Pedro";
int edad = 40;
string mensaje = $"Hola, mi nombre es {nombre} y tengo {edad} años.";

Console.WriteLine(mensaje);
Copied!

Interpolation is usually more readable than String.Format indices, especially when several values appear.

The same specifiers work inside an interpolated string:

double precio = 12.3498;
string mensaje = $"El precio es: {precio:F2}";

Console.WriteLine(mensaje);
Copied!
El precio es: 12.35
Copied!

Formatting with ToString()

Types that support formatting offer overloads of ToString() with which we can control their representation. It’s common to use them with numbers, dates, and times.

DateTime fecha = new DateTime(2025, 12, 12, 15, 30, 45);
string texto = fecha.ToString("yyyy-MM-dd HH:mm:ss");

Console.WriteLine(texto);
Copied!
2025-12-12 15:30:45
Copied!

Note that some specifiers depend on the current culture. If the format must be stable for data interchange, explicitly indicate the appropriate culture.

Joining Multiple Values

String.Concat concatenates several values without a separator. It is equivalent to chaining the + operator in many cases:

string mensaje = string.Concat("Nombre: ", nombre, ", edad: ", edad);
Copied!

On the other hand, String.Join inserts a separator between the elements of a collection:

string[] nombres = { "Juan", "Ana", "Pedro", "María" };
string mensaje = string.Join(", ", nombres);

Console.WriteLine(mensaje);
Copied!
Juan, Ana, Pedro, María
Copied!

Building Strings with StringBuilder

When we modify a string many times, for example inside a loop, StringBuilder avoids creating an intermediate string in each operation.

using System.Text;

StringBuilder sb = new StringBuilder();

for (int i = 1; i <= 5; i++)
{
    sb.AppendLine($"Número {i}");
}

string resultado = sb.ToString();
Copied!

This can be more efficient in large or repetitive constructions. For a few concatenations, clarity usually takes precedence and there’s no need to introduce StringBuilder.

Common Numeric Specifiers

Standard specifiers cover the most common formats:

SpecifierUsageExample
CCurrency{precio:C2}
DDecimal integer with zeros{numero:D4}
FFixed point{valor:F2}
NNumber with separators{valor:N2}
PPercentage{proporcion:P1}
XHexadecimal{numero:X}

The number following the letter usually indicates precision. For example, F2 shows two decimal places and D4 pads an integer with zeros to reach four digits.

Aligning Values

Inside a placeholder, you can specify a minimum width after a comma. A positive value aligns to the right and a negative one to the left:

string nombre = "Juan";
int edad = 25;

string mensaje = string.Format(
    "Nombre: {0,-10} Edad: {1,5}",
    nombre,
    edad);

Console.WriteLine(mensaje);
Copied!

Alignment is useful for generating text columns, logs, or console outputs without manually constructing the spaces.