Search code examples
c#.netstringformattingstring-formatting

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


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.


Solution

  • 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.