Reputation: 117
I am trying to retrieve an element from dropdown and storing in a string
. I want to convert that string
currency symbol to currency code. Following is the code i wrote:
I wrote below code but i am getting an error message :
System.Globalization.CultureNotFoundException: Culture is not supported. Parameter name: name USD - United States dollar is an invalid culture identifier.
public string RetreiveCurrencySymbolFromCode()
{
string currencycode = " USD-United States Dollars";
string FinalCode = Currencycode1.Split('-')[0];
CultureInfo Symbol = new CultureInfo(FinalCode);
return Symbol.NumberFormat.CurrencySymbol;
}
I expect to retrieve USD and change it to symbol $
Upvotes: 2
Views: 1708
Reputation: 186803
Well, "USD"
is name of a currency (RegionInfo.ISOCurrencySymbol
), when "en-US"
is an (expected) name of a culture (Culture.Name
). Let's obtain all cultures that use USD
as a currency:
string FinalCode = "USD";
var result = CultureInfo
.GetCultures(CultureTypes.SpecificCultures)
.Where(culture => new RegionInfo(culture.LCID).ISOCurrencySymbol == FinalCode)
.ToArray();
Console.Write(string.Join(Environment.NewLine, result
.Select(culture => $"{culture.Name,10} : ({culture.NumberFormat.CurrencySymbol}) : {culture.EnglishName}")));
Outcome:
en-US : ($) : English (United States)
quz-EC : ($) : Quechua (Ecuador)
en-029 : ($) : English (Caribbean)
es-EC : ($) : Spanish (Ecuador)
es-SV : ($) : Spanish (El Salvador)
es-PR : ($) : Spanish (Puerto Rico)
es-US : ($) : Spanish (United States)
As you can see several different cultures can use the same currency. Technically, you code can be implemented as
using System.Text.RegularExpressions;
...
string currencycode = " USD-United States Dollars";
...
// https://en.wikipedia.org/wiki/ISO_4217
// ISO_4217 - all codes are 3 capital letters
string FinalCode = Regex.Match(currencycode, "[A-Z]{3}").Value;
var culture = CultureInfo
.GetCultures(CultureTypes.SpecificCultures)
.Where(culture => new RegionInfo(culture.LCID).ISOCurrencySymbol == FinalCode)
.FirstOrDefault();
if (culture != null)
return culture.NumberFormat.CurrencySymbol;
else
return "???"; // Unknown currency / culture
There are 2 issues here:
USD
, EUR
, RUB
), a safier approach is to Match
with a help of regular expressionsUpvotes: 4