Shahin
Shahin

Reputation: 12843

Add comma to numbers every three digits using C#

I want to add comma to decimal numbers every 3 digits using c#.
I wrote this code :

double a = 0; 
a = 1.5;
Interaction.MsgBox(string.Format("{0:#,###0}", a));

But it returns 2.
Where am I wrong ?
Please describe how can I fix it ?

Upvotes: 9

Views: 13873

Answers (6)

Richard Szalay
Richard Szalay

Reputation: 84744

There is a standard format string that will separate thousand units: N

float value = 1234.512;

value.ToString("N"); // 1,234.512
String.Format("N2", value); // 1,234.51

Upvotes: 4

Waqas Raja
Waqas Raja

Reputation: 10872

Did you tried by this:-

string.Format("{0:0,000.0}", 1.5);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

Try the following format:

string.Format("{0:#,0.0}", a)

Upvotes: 2

InBetween
InBetween

Reputation: 32750

Its doing it right. #,##0 means write at least one digit and zero decimals and space digit groups with comas. Therefore it rounds 1.5 to 2 as it cant write decimals. Try #,##0.00 instead. You'll get 1.50

Upvotes: 2

Hogan
Hogan

Reputation: 70523

Here is how to do it:

 string.Format("{0:0,0.0}", a)

Upvotes: 4

Bala R
Bala R

Reputation: 108957

 double a = 1.5;
Interaction.MsgBox(string.Format("{0:#,###0.#}", a));

Upvotes: 9

Related Questions