2

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?

tapizquent
  • 668
  • 11
  • 24
  • You’ll have to map the currency to a culture – Daniel A. White Jul 11 '22 at 22:55
  • i suspect you are goinjg to need a dictionary mapping currenies to locale names ie USD=>en-US, GBP=>en-UK.... – pm100 Jul 11 '22 at 22:55
  • I think your question looks like `Globalization and localization in asp.net core`, Maybe you can refer to this [ssue](https://learn.microsoft.com/en-us/answers/questions/433479/setting-currency-independent-of-culture.html). – Xinran Shen Jul 12 '22 at 09:15

1 Answers1

1

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

gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • Side note: while this answers the question OP has, it is a wrong suggestion if one looking for correct results. Unfortunately there is no way to code "use this culture's currency formatting but a different currency symbol". As result everyone grabs a somewhat random culture that happen to use the given currency and formats the value with that... ending up with "2.5 apples will cost you 2,50$" :( – Alexei Levenkov Jul 11 '22 at 23:27