C# .NET: String Format a Number with Commas

11/25/2013 9:33:30 PM

.NET Framework

The following will take an int, long, double, or decimal and display that number as a string with a comma separator. If the number has decimal places (double or decimal), it will display the decimal places as well. If you need to round the number to a certain number of decimal places, there are multiple overloaded methods.

public static string DisplayNumberWithCommas(int value)
{
	return DisplayNumberWithCommas((decimal)value, 0);			
}
public static string DisplayNumberWithCommas(long value)
{
	return DisplayNumberWithCommas((decimal)value, 0);
}
public static string DisplayNumberWithCommas(double value)
{
	return DisplayNumberWithCommas((decimal)value);
}
public static string DisplayNumberWithCommas(double value, int decimalPlaces = 0, System.MidpointRounding midPointRounding = MidpointRounding.AwayFromZero)
{
	return DisplayNumberWithCommas((decimal)value, decimalPlaces, midPointRounding);
}		
public static string DisplayNumberWithCommas(decimal value, int decimalPlaces = 0, System.MidpointRounding midPointRounding = MidpointRounding.AwayFromZero)
{
	//round value
	value = Math.Round(value, decimalPlaces, midPointRounding);

	return DisplayNumberWithCommas(value);
}
public static string DisplayNumberWithCommas(decimal value)
{
	string stringFormat = "#,##0";
	string toString = value.ToString();
	if (toString.Contains("."))
	{
		//if contains ".", there is a value after the decimal, therefore + 1
		string sub = toString.Substring(toString.IndexOf(".") + 1);				

		//length of the substring represents the precision of the decimal
		for (int x = 0; x <= sub.Length; x++)
		{
			 if (x == 0)
			 {
				 //must add "." to format
				 stringFormat += ".";    
			 }   
			 else                 
			 {
				 stringFormat += "0";
			 }
		}
	}

	return value.ToString(stringFormat);			
}