How to Convert a Number to a Comma-Separated String in C#?

In this C# tutorial, I will explain, how to convert a number to comma separated string in C#.

There are 3 different methods to convert a number to a comma-separated string in C#.

  • using ToString()
  • using String.Format()
  • using StringBuilder

Convert a Number to a Comma-Separated String in C#

Let us check the 3 methods to convert a number to a comma-separated string in C#.

Using ToString()

The simplest way to convert a number into a comma-separated string in C# is by using the ToString() method with the format “N” followed by the number of decimal places you want.

using System;

class Program
{
    static void Main()
    {
        int num = 1234567890;
        string str = num.ToString("N0");
        Console.WriteLine(str);  // Output: 1,234,567,890
    }
}

Here, N0 indicates that we want the number formatted with commas and zero decimal places.

You can check the output after I run the code using Visual Studio.

Convert a Number to a Comma-Separated String in C#

Using String.Format()

If you want more control over the string format, you can use the String.Format method in C#. This method provides a variety of options for string interpolation and formatting.

using System;

class Program
{
    static void Main()
    {
        int num = 1234567890;
        string str = String.Format("{0:N0}", num);
        Console.WriteLine(str);  // Output: 1,234,567,890
    }
}

You can see the output below in the screenshot after I run the code using a Windows application in C#.

How to Convert a Number to a Comma-Separated String in C#

Using StringBuilder

Although StringBuilder is more commonly used for complex string manipulations, you can use it for converting a number to a comma-separated string in C#. However, this approach is generally overkill for simply adding commas to a number.

Here is a complete code for the same.

using System;
using System.Text;

class Program
{
    static void Main()
    {
        int num = 1234567890;
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat("{0:N0}", num);
        string str = sb.ToString();
        Console.WriteLine(str);  // Output: 1,234,567,890
    }
}

You can see the output below:

C# Convert a Number to a Comma-Separated String

Here is a small comparison of various methods.

MethodComplexityFlexibilityUse-case
ToString()LowLowQuick formatting with limited options
String.Format()MediumHighDetailed control over formatting
StringBuilderHighHighComplex string manipulations, generally overkill for this task

Conclusion

Converting numbers to comma-separated strings in C# can be done in multiple ways, each with its own set of advantages and limitations. While ToString() is simple and straightforward, String.Format() and StringBuilder offer more control over formatting.

In this C# tutorial, I have explained, how to convert a number to a comma-separated string in C#.

You may like the following C# tutorials: