LostPhysx
LostPhysx

Reputation: 3641

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.

Upvotes: 3

Views: 18934

Answers (3)

AaR
AaR

Reputation: 11

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});

Upvotes: 1

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 62002

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.

Upvotes: 9

LostPhysx
LostPhysx

Reputation: 3641

Ok, I solved the problem with:

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

Upvotes: 4

Related Questions