16

How to display a numeric numbers in 3 digit groupings.

For Ex: 1234 to be 1,234 or 1 234

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Santhosh
  • 19,616
  • 22
  • 63
  • 74
  • possible duplicate of [.NET String.Format() to add commas in thousands place for a number](http://stackoverflow.com/questions/105770/net-string-format-to-add-commas-in-thousands-place-for-a-number) – Helen Apr 24 '14 at 08:02

8 Answers8

22

From the The Numeric ("N") Format Specifier section in Standard Numeric Format Strings:

double dblValue = -12445.6789;
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture));
// Displays -12,445.68

Console.WriteLine(dblValue.ToString("N1", 
                  CultureInfo.CreateSpecificCulture("sv-SE")));
// Displays -12 445,7

int intValue = 123456789;
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture));
// Displays 123,456,789.0 
Alek Davis
  • 10,628
  • 2
  • 41
  • 53
14

Try this:

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

If you want spaces instead of commas try this:

String.Format("{0:n0}", yourNumber).Replace(",", " ");

Edit: Marc makes a good point about being cuturally aware so this would be a better way to replace the group separators:

String.Format("{0:n0}", yourNumber)
    .Replace(NumberFormatInfo.CurrentInfo.NumberGroupSeparator, " ");
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
6

The comma case is easy enough - .ToString("###,###,###"); for the space? perhaps cheat and replace the commas? Or write a custom culture with space as the group separator?

Note also that this is culture-dependent. The comma above doesn't mean "comma", it means the culture's group separator. You might want to specify a fixed culture if this matters (perhaps the invariant culture).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
5

You can use

yourDecimal.ToString("#,##0");

or

yourDecimal.ToString("#,##0.00");

for decimal places.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
2

Compare those:

 .ToString("#,##0", new System.Globalization.CultureInfo("en-US"))

 .ToString("#,##0", new System.Globalization.CultureInfo("fr-FR"))

 .ToString("#,##0", new System.Globalization.CultureInfo("de-DE"))

 .ToString("#,##0")

I hope it will help.

Nerevar
  • 156
  • 1
  • 7
2

use this sample code:

int test1 = 123456;
string test2 = test1.ToString("N0");

output= 123,456

Roohollah
  • 69
  • 7
1

You Can simply Use Visual Basic TriState for it For Example:

textBox1.Text = Microsoft.VisualBasic.Strings.FormatNumber(textBox1.Text, 0, TriState.True);

String formatting was not what i needed! but this one done what i wanted! hope it solves your problem too :)

ACE
  • 379
  • 3
  • 12
0

Also this code:

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

Would result: 1,234,567

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
gyousefi
  • 306
  • 3
  • 9