9

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 ?

Shahin
  • 12,543
  • 39
  • 127
  • 205

6 Answers6

9
 double a = 1.5;
Interaction.MsgBox(string.Format("{0:#,###0.#}", a));
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • It is right thank you ,would you please describe about first argument of string.Format ? – Shahin May 28 '11 at 11:12
  • In your format string you weren't addressing the decimal part of the number so it was rounding it off to 2. So the .# In the format string addresses that and if always want decimal part to be displayed, even for, say 2.0 then use .0 in the format string. – Bala R May 28 '11 at 11:19
  • I have a question: is the format in the answer is different from `#,0.#`? – Alex Aza May 28 '11 at 20:21
4

Here is how to do it:

 string.Format("{0:0,0.0}", a)
Hogan
  • 69,564
  • 10
  • 76
  • 117
4

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
Richard Szalay
  • 83,269
  • 19
  • 178
  • 237
2

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

InBetween
  • 32,319
  • 3
  • 50
  • 90
2

Try the following format:

string.Format("{0:#,0.0}", a)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • It works , but for number 10 it returns 10.0 , should i replace 10.0 with nothing or it is possible to improve string.Format function ? – Shahin May 28 '11 at 11:20
  • @shaahin, string formats for doubles are nicely explained in [this article](http://www.csharp-examples.net/string-format-double/). As far as 10.0 is concerned if you don't want the decimal if it is 0 you could use `{0:#,#.#}`. – Darin Dimitrov May 28 '11 at 11:20
1

Did you tried by this:-

string.Format("{0:0,000.0}", 1.5);
Waqas Raja
  • 10,802
  • 4
  • 33
  • 38