Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print integer with comma as thousands separator (1234567 to "1,234,567") [duplicate]

Tags:

c#

I have an integer that needs to be converted to a string with thousands separated by comma. I tried

string.Format("{0:n}", 999999)

However, the output I get is "999,999.00". I don't want the ".00" part to appear.

like image 870
derin Avatar asked Nov 30 '22 04:11

derin


1 Answers

You could specify 0 as the precision:

string x = string.Format("{0:n0}", 999999);
Console.WriteLine(x);

or more simply if you don't really need it within a bigger format string:

string x = 999999.ToString("n0");
Console.WriteLine(x);

Note that this will use the default "thousand separator" for the current culture. If you want to force it to use commas, you should probably specify the culture explicitly:

string x = 999999.ToString("n0", CultureInfo.InvariantCulture);
Console.WriteLine(x);

I wouldn't personally describe this as "comma-separated" by the way - that's usually used to describe a format which combines multiple different values. I'd just talk about this "including comma as a thousand separator".

like image 139
Jon Skeet Avatar answered Dec 16 '22 11:12

Jon Skeet