-2

I'm not able to convert float to the currency string. I tried to find an answer on the internet.

float price = 29.95f;
Console.WriteLine(price.ToString("C"));

Outputs:

29,95 ?

P.S. Problem is with my console.

  • 5
    And does the codepage of your console support the currency symbol for your current culture? I would hazard a guess that the conversion is fine, it is `Console.WriteLine` and the console running your program that is at flaw here, it doesn't have a proper symbol for the currency symbol and thus just displays a question mark instead. – Lasse V. Karlsen Jan 02 '20 at 13:18
  • 1
    *Which* culture is this for by the way? – Lasse V. Karlsen Jan 02 '20 at 13:18
  • 4
    Incidentally, the `float` type is not often accurate enough for money. The `decimal` type is, and should be used. – Andrew Morton Jan 02 '20 at 13:24
  • 1
    Also best to double check your currency symbol in Control Panel \ Region - in case for whatever reason it is missing. – Ryan Thomas Jan 02 '20 at 13:24

2 Answers2

0

As indicated in comments by Lasse, you may be missing a culture:

Try:

Console.WriteLine(price.ToString("C", CultureInfo.CurrentCulture));

For a specific culture, you can try:

price.ToString("C", new CultureInfo("en-GB")); // for uk culture..

decimal is usually the recommendation for currency.

See more here:

Why not use Double or Float to represent currency?

Gauravsa
  • 6,330
  • 2
  • 21
  • 30
0

You should use decimal instead of float for currency because it is more accurate. Anyway your code is fine and it must be a display error.

// Declare price as a decimal.
decimal price = 29.95m;

You can also specify cultures using:

// For German culture.
Console.WriteLine(price.ToString("C", new CultureInfo("en-DE")));

// Output
// 29,95 €

// For British culture.
Console.WriteLine(price.ToString("C", new CultureInfo("en-GB")));

// Ouput
// £29.95

// For American culture.
Console.WriteLine(price.ToString("C", new CultureInfo("en-US")));

// Output
// $29.95

Edit: Just saw your update, glad it was just a display issue. Also, I think you should give this a read. It is better to accept an answer (even if you have to leave your own) rather than edit your post.