0

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!

Benjamin
  • 3
  • 2
  • 1
    [Possible duplicate of Format decimal as currency based on currency code](https://stackoverflow.com/questions/13364984/format-decimal-as-currency-based-on-currency-code/30628398) – ProgrammingLlama Feb 04 '20 at 08:38

1 Answers1

3

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.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
  • Thank you for your answer. But I want show 3 digits, if 3 digits exists. And if exists only 2 digits, I want show 2 digits. But I see, that this in combination with the currency specifier C is not possible... – Benjamin Feb 04 '20 at 15:48