Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the currency modifier "C" returning '?' instead of '$' in C#?

Tags:

c#

Why does the code below display '?' instead of '$'?

static void Main(string[] args)
{
    float price = 29.56f;
    Console.WriteLine(price.ToString("c"));
}

The result is: 29,56 ?

like image 249
Chubini Avatar asked May 29 '19 18:05

Chubini


1 Answers

It's not an actual ? character - that's a placeholder being printed in the console because the current console font doesn't have a glyph for whatever the local currency's currency symbol is (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol).

If you always want US Dollars, then format using the en-US culture:

CultureInfo enUS = new CultureInfo("en-US");
String priceText = price.ToString( "C", enUS );
Console.WriteLine( priceText );

Don't use en-US for other cultures, even if they use Dollars too (e.g. Australian dollars), instead use their culture explicitly - so your program will still work if in the future the country changes their currency symbol, or if they have other formatting rules (e.g. a different decimal symbol)

CultureInfo australia = new CultureInfo("en-AU");
String priceText = price.ToString( "C", australia );
Console.WriteLine( priceText );

Additionally, you should not use IEEE-754 types when working with currency or monetary values because it’s imprecise by design. You should always use a fixed decimal type like System.Decimal or integer cents (though you can’t use ”C” forest strings with integer cents)

like image 135
Dai Avatar answered Oct 30 '22 01:10

Dai