ShadowG
ShadowG

Reputation: 683

Formatting strings into groups of 3 digits by periods

I know I can format strings using the String.Format() method. Is it possible to format like this?

Example:

string: 1568
formatted: 1.568

string: 168794521
formatted: 168.794.521

string: 987
formatted: 987

Sorry that I can't make myself more clear.

Upvotes: 3

Views: 1335

Answers (3)

Muad'Dib
Muad'Dib

Reputation: 29226

Yes, you can do that. SteveX has written a great blog post on string formatting. You could also look at this blog post, and the MSDN documentation.

You probably want to look at the bottom of this documentation in the "More Resources" section for more info about different types of standard format strings.

Here is the relavant part from the SteveX blog on formatting numbers:

  • Currency {0:c}
  • Decimal (Whole number) {0:d}
  • Scientific {0:e}
  • Fixed point {0:f}
  • General {0:g}
  • Number with commas for thousands {0:n}

Upvotes: -1

Reed Copsey
Reed Copsey

Reputation: 564451

You can format a number that way, but not a string. For example, if you have an integer value, you can use:

int value = 168794521;
string formatted = value.ToString("N0");

With the proper culture, this will format as shown.

If you are using a string, you would need to convert it. You could also explicitly provide a culture to guarantee "." as a thousands separator:

int value = Int32.Parse("168794521");
string formatted = value.ToString("N0", new CultureInfo("de-DE"));

Upvotes: 9

McKay
McKay

Reputation: 12614

string someNumericValue = "168794521";
int number = int.Parse(someNumericValue); // error checking might be appropriate
value.ToString("0,0", CultureInfo.CreateSpecificCulture("el-GR"));

This will put points in for thousand specifiers.

It's possible that if you want this, your culture may already do this.

Upvotes: 5

Related Questions