views:

52

answers:

4
  • How, for example, do I turn the number 10562.3093 into 10,562 in C#?
  • Also, how do I ensure that same formatter will apply correctly to all other numbers?....
  • ...For example 2500.32 into 2,500

Help greatly appreciated.

+1  A: 
String.Format("{0:0,0}", 10562.3093);

I keep this website bookmarked for these purposes: String Formatting in C#

drharris
Using "0,0" will prefix single digit numbers with a 0: String.Format("{0:0,0}", 2.3093); results in "02", using "#,#" instead will prevent this.
Phil Lamb
Won't work either: 0 will turn into nothing. You should use either `N0` or `#,0`.
Ruben
+1  A: 
string.Format("{0:n0}", 10562.3093);
dcp
A: 
double x = 10562.3093;
x.ToString("#,0");

or

String.Format("{0:#,0}", 10562.3093);
Phil Lamb
Won't work either: 0 will turn into nothing. You should use either `N0` or `#,0`.
Ruben
Edited, I didn't consider that case.
Phil Lamb
+1  A: 
string formatted = value.ToString("N0");

This divides your number in the manner specified by the current culture (in the case of "en-US," it's a comma per multiple of 1000) and includes no decimal places.

The best place to look for any question regarding formatting numbers in .NET would have to be here:

Standard Numeric Format Strings (MSDN)

And here:

Custom Numeric Format Strings (MSDN)

Dan Tao