Pregunta

Well... i search the web and found many solutions for the other way, but none for these.

I have a application which gets different currencys by the user. I dont know the currencys in before, it could be everything (russian rubels, usd, €, Yen...)

I need to convert the amount into a decimal, for that i need the current culture. My current solution is very bad 8and incomplete, cause i cant cover all cultures that way), it just checks the currency sign.

if (currency.Contains("zł"))
{
    cult = CultureInfo.GetCultureInfo("PL-pl")
}
else if (currency.Contains("$"))
{
    //blah blah blah
}

Is there a possiblility to get Culture base on the currency sign. Another maybe difficult thing is, that i dont know if the currency symbol is before or beyond the amount (varys by culture i.E: $45.00 <-> 45.00€)

¿Fue útil?

Solución

Create a lookup once and use it for fast access. Notice that a particular currency symbol may be used by multiple cultures:

ILookup<string, CultureInfo> cultureByCurrency = 
    CultureInfo.GetCultures(CultureTypes.AllCultures)
    .ToLookup(_ => _.NumberFormat.CurrencySymbol);

Then to lookup $ for example:

IEnumerable<CultureInfo> culturesThatUseDollar = cultureByCurrency["$"];

Otros consejos

There is no exact mapping from a currency code or symbol to a culture. Consider basic examples like EUR (€), which is used as the official currency in 18 countries. There are many issues arising from this mere fact, like whether the symbol is placed before or after the value etc. You should ask the user about the specific formatting to use instead of trying to deduce it from the currency symbol.

Also, a single currency symbol is used for many currencies. Consider that $ can denote both USD, CAD, AUD and other currencies that call themselves as 'dollars'. You should use currency codes if you want an exact specification of a currency.

It is not possible.

EUR for example would map to de-DE, fr-FR, nl-NL and other countries.

There is no mapping from Currency to culture, because multiple countries share currencies

In your else if block, which culture would you assign after finding the $? en-US? fr-CA?

I would suggest a different approach that would remove any sort of ambiguity. Have the user specify their nationality before entering this chunk of code. Consider having the culture information given to you instead of attempting to guess it.

return CultureInfo.GetCultures(CultureTypes.AllCultures).Where(c => c.NumberFormat.CurrencySymbol.Equals("$"));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top