Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add commas using String.Format for number and

Tags:

c#

Using String.Format how can i ensure all numbers have commas after every 3 digits eg 23000 = "23,000" and that 0 returns "0".

String.Format("{0:n}", 0); //gives 0.00 which i dont want. I dont want any decimal places, all numbers will be integers.

like image 617
raklos Avatar asked Mar 30 '10 13:03

raklos


People also ask

How can I format a string number to have commas?

For format String "%,. 2f" means separate digit groups with commas and ".

How do you add a comma to a string number in Python?

In Python, to format a number with commas we will use “{:,}” along with the format() function and it will add a comma to every thousand places starting from left. After writing the above code (python format number with commas), Ones you will print “numbers” then the output will appear as a “ 5,000,000”. Here, {:,}.

How do I add a comma between numbers in Java?

You can use java. util. text. NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them.


3 Answers

You can do this, which I find a bit cleaner to read the intent of:

String.Format("{0:#,###0}", 0); 

Example:

string.Format("{0:#,###0}", 123456789); // 123,456,789 string.Format("{0:#,###0}", 0); // 0 
like image 97
Nick Craver Avatar answered Sep 20 '22 08:09

Nick Craver


If your current culture seting uses commas as thousands separator, you can just format it as a number with zero decimals:

String.Format("{0:N0}", 0)

Or:

0.ToString("N0")
like image 27
Guffa Avatar answered Sep 22 '22 08:09

Guffa


from msdn

double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));

Displays 1,234,567,890

like image 25
pierroz Avatar answered Sep 18 '22 08:09

pierroz