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 ?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With