How to format a string with thousands separation and decimal comma?

18,236

Solution 1

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.

Solution 2

Ok, I solved the problem with:

string.Format("{0:0,0.00}", Convert.ToDouble(amount))

Solution 3

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});
Share:
18,236
LostPhysx
Author by

LostPhysx

Updated on June 05, 2022

Comments

  • LostPhysx
    LostPhysx almost 2 years

    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.

  • Jeppe Stig Nielsen
    Jeppe Stig Nielsen over 10 years
    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).
  • Titwan
    Titwan almost 6 years
    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 });