In Angular, the currency pipe converts the value for AUD as A$
. using this code for example:
{{ total | currency : 'AUD' : 'symbol' }} // output as A$100.00
How to achieve this in C#? I've done my research but for AUD it just output it as $
. This is by using toString with culture info
total.ToString("C2", CultureInfo.GetCultureInfo("en-AU")) // output as $100.00
CodePudding user response:
You are doing it right. Australians on this website say this ($) is the correct symbol: https://www.studymelbourne.vic.gov.au/money-and-budgeting/australian-currency
EDIT: Or just make a custom method:
public static DecimalExtensions {
public static string ToCurrencyWithSymbol( this decimal n, string culture ) {
if( culture == 'en-AU')
return "A" n.ToString("C2", CultureInfo.GetCultureInfo("en-AU"));
else n.ToString("C2", CultureInfo.GetCultureInfo(culture));
}
}
CodePudding user response:
Your angular snippet formats the total as AUD using the current locale. In en-US, this ends up being A$. In the Australian locale, however, the currency symbol is just $.
The .NET framework does not offer a way to do this out of the box. Whenever .ToString
's C2
format is used together with a CultureInfo
object, it will use the currency symbol that's appropriate for the given locale. Unfortunately this means that all dollar currencies, no matter what variety (USD, CAD, AUD, NZD, etc.) all end up as $ because that is what their respective locale uses.
The easiest way to solve this is probably to write something custom that will do the formatting for you, somewhere along the lines of this:
public static Dictionary<string, string> CurrencyDict = new Dictionary<string, string>( )
{
{ "AUD", "A$" },
{ "CAD", "C$" },
{ "EUR", "€" },
{ "USD", "$" },
//etc
};
public static string ToCurrency( this decimal amount, string currency = null )
{
if ( currency != null && CurrencyDict.TryGetValue( currency, out string currencySymbol ) )
{
return $"{currencySymbol} {amount:N}";
}
else //default to current locale
{
return amount.ToString( "C2", CultureInfo.CurrentCulture );
}
}