How to format string as currency given the currency code/symbol

Viewed 63

I am trying to format a string as a currency given the currency code and not the locale. That is, given USD and not en_US.

I have seen examples on how to format it using value.ToString(CultureInfo.CreateSpecificCulture("en-US")) but something like this does not work value.ToString(CultureInfo.CreateSpecificCulture("USD"))

Is there any way to format the string as such?

1 Answers

You'll need to create a map of all Cultures with their corresponding ISOCurrencySymbol value.

ILookup<string, CultureInfo> cultureByCurrency = 
    CultureInfo.GetCultures(CultureTypes.SpecificCultures)
    .Where(x => { try { _ = new RegionInfo(x.LCID); return true; } catch { return false; }})
    .ToLookup(x => new RegionInfo(x.LCID).ISOCurrencySymbol);
cultureByCurrency["USD"].First().Name; // "en-US"
cultureByCurrency["CNY"].First().Name; // "bo-CN"

foreach (var culture in cultureByCurrency["EUR"])
{
    Console.WriteLine(culture.Name);
}
// gives br-FR ca-ES de-AT de-DE de-LU dsb-DE el-GR en-IE es-ES et-EE eu-ES fi-FI fr-BE fr-FR fr-LU
// fr-MC fr-RE fy-NL ga-IE gl-ES gsw-FR hsb-DE it-IT lb-LU lt-LT lv-LV mt-MT nl-BE
// nl-NL pt-PT se-FI sk-SK sl-SI smn-FI sr-Cyrl-ME sr-Latn-ME sv-FI

The Where is... well, it's a bit jank. Apparently there are some cultures from SpecificCultures that don't have an ISOCurrencySymbol, so that filters out those that can't be looked up.

More info about the lookup here, and the ISOCurrentySymbol property here

Related