ssl
ssl

Reputation:

How do I format a number with commas?

int a = 10000000;
a.ToString();

How do I make the output?

10,000,000

Upvotes: 51

Views: 57937

Answers (6)

Max
Max

Reputation: 1912

Even simpler for c#6 or higher:

string formatted = $"{a:N0}";

Upvotes: 2

Willy David Jr
Willy David Jr

Reputation: 9151

You can also do String.Format:

int x = 100000;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000

If you have decimal, the same code will output 2 decimal places:

double x = 100000.2333;
string y = string.Empty;
y = string.Format("{0:#,##0.##}", x); 
//Will output: 100,000.23

To make comma instead of decimal use this:

double x = 100000.2333;
string y = string.Empty;
y = string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:#,##0.##}", x);

Upvotes: 12

pistol-pete
pistol-pete

Reputation: 1261

A simpler String.Format option:

int a = 10000000;
String.Format("{0:n0}", a); //10,000,000

Upvotes: 3

lc.
lc.

Reputation: 116528

a.ToString("N0")

See also: Standard Numeric Formatting Strings from MSDN

Upvotes: 11

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827942

Try N0 for no decimal part:

string formatted = a.ToString("N0"); // 10,000,000

Upvotes: 90

Mike
Mike

Reputation: 5281

a.tostring("00,000,000")

Upvotes: -3

Related Questions