tags:

views:

134

answers:

4
+2  Q: 

c# string format

Hi Guys,

How do I get the output of this to read 0 instead of 00 when the value is 0?

String.Format("{0:0,0}", myDouble);
+2  A: 
string.Format("{0:#,0}", myDouble);

(tested version)

Dan Dumitru
This will an empty string for 0.
Matthew Flaschen
Well, it took me some time before I fired up Visual Studio, but now I *did* test it.
Dan Dumitru
I find Mono's [C# REPL](http://www.mono-project.com/CsharpRepl) comes in handy for quick testing like this.
Matthew Flaschen
@Matthew - Well, if I'd go that way, I'd might as well use a text file and the command prompt, as Jon Skeet says he does :) But otherwise it seems as an interesting app, thanks for the link.
Dan Dumitru
+2  A: 
String.Format("{0:#,0}", myDouble);
Matthew Flaschen
+1: This was the first *working* answer.
Mark Byers
Yes, indeed. To my defense, I can say that I first checked in Visual Studio, and then when I came back to correct my answer I saw Matthew had posted his, but hmm, who would believe me...
Dan Dumitru
+1  A: 

Another alternative is to use this:

string s = string.Format("{0:n0}", myDouble);

If you always want commas as the thousands separator and not to use the user's locale then use this instead:

string s = myDouble.ToString("n0", CultureInfo.InvariantCulture);
Mark Byers
+1  A: 

While the posted answers here ("{0:#,0}") are correct I would strongly suggest using a more readable picture (also to avoid confusion about decimal/thousand separators):

string.Format("{0:#,##0}", v);     // to print 1,234
string.Format("{0:#,##0.00}", v);  // to print 1,234.56

But all those pictures work the same, including 2 comma's for 1e6 etc.

Henk Holterman
+1: Good point.
Mark Byers