Reputation: 3
I'ts possible to format a number to a currency with differend decimals?
For example:
// for numbers I can use the placeholder #
decimal d1 = 1.2345;
decimal d2 = 1.23;
String.Format("{0:0.####}", d1); //results in 1.2345
String.Format("{0:0.####}", d2); //results in 1.23
// with the format specifier C I cannot use the placeholder
String.Format("{0:C4}", d1); //results in 1.2345 €
String.Format("{0:C4}", d2); //results in 1.2300 €
// I need something like this
String.Format("{0:C####}", d1); //results in 1.2345 €
String.Format("{0:C####}", d2); //results in 1.23 €
// I don't want to use this solution because I use my program in different countries
String.Format("{0:0.#### €}", d1); //results in 1.2345 €
String.Format("{0:0.#### €}", d2); //results in 1.23 €
Anyone have an idea?
Thank you!
Upvotes: 0
Views: 144
Reputation: 5634
Here is your answer:
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
If you want more than 2 decimal digits (let's say 3 digits after decimal points), then it would be
double value = 12345.6789;
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
This is assuming that your application will be executed under different cultures. That's why we used currentCulture
.
Otherwise you can create instance of CultureInfo
depending on the culture you want to use.
Refer this documentation for number formatting and this page for more details on CultureInfo
.
Upvotes: 3