3

I have some strings:

string amount = "123456";
string amount2 = "123456.78";

I want the output to be:

amount: 123.456,00
amount2: 123.456,78

I already looked here, but this does not work for my example.

Community
  • 1
  • 1
LostPhysx
  • 3,573
  • 8
  • 43
  • 73

3 Answers3

9

You can use:

decimal.Parse(amount).ToString("N")

This assumes your culture uses the format you want. You can specify a culture explicitly, for example:

decimal.Parse(amount, CultureInfo.InvariantCulture)
    .ToString("N", new CultureInfo("de-DE"))

for the culture "German (Germany)" ("de-DE"). Edited to specify format provider for the Parse method as well.

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
4

Ok, I solved the problem with:

string.Format("{0:0,0.00}", Convert.ToDouble(amount))
LostPhysx
  • 3,573
  • 8
  • 43
  • 73
  • 1
    This of course is equivalent to `Convert.ToDouble(amount).ToString("0,0.00")`. But as I said in my answer, `"N"` can also be used instead of `"0,0.00"` (or `"N2"` in the rare occasion where the culture has `NumberDecimalDigits` distinct from `2`). – Jeppe Stig Nielsen Sep 13 '13 at 19:58
1

Alternativly, the following also enables easy user-customization what was a requirement for my app.

string groupSeperator = ".";
string decimalSeperator = ",";
int decimalDigits= 2;

decimal.Parse(amount).ToString("N", new NumberFormatInfo{NumberDecimalSeparator = decimalSeperator , NumberDecimalDigits = decimalDigits, NumberGroupSeparator = groupSeperator});
AaR
  • 11
  • 3
  • Perfect snippet solution !!! copy paste --> works ! You are great !!! We can really define or customize the number format as wished. For me it was like: string groupSeperator = "'"; string decimalSeperator = "."; int decimalDigits = 0; var s_TotalWordCount = m_TotalWordCount.ToString("N", new NumberFormatInfo { NumberDecimalSeparator = decimalSeperator, NumberDecimalDigits = decimalDigits, NumberGroupSeparator = groupSeperator }); – Titwan Jul 13 '18 at 07:41