问题
I have a Xamarin.Forms app that is obtaining a 2-letter ISO country code for GeoLocation. I need the app to display currency in the local style. So if I took my phone from the UK to Japan it would display currency fields formatted up in Yen.
The most straight forward way to format a decimal currency is to use a CultureInfo object.
How can I get to a CultureInfo object from a 2-letter ISO country code. I have been trying to achieve this for quite a few days, but cannot find a path of conversions.
Any pointers?
回答1:
var isoCountryCode = "GB"; // Replace with the one you got from GeoLocation.
var cultureInfo = CultureInfo.GetCultures(CultureTypes.AllCultures)
.Where(c => c.Name.EndsWith("-" + isoCountryCode )).First;
If you check the list of CultureCodes provided by microsoft you can see that the first two letters of the culture refer to language and the last two to country. For example, for japanese you would have "ja" and "ja-JP").
Therefore if you search through the list of cultures for the ones that end with your desired country code, you should get a list of all available CultureInfo for your desired country.
Then you can either go through them again to find the one for the users selected language (if available) or pick one arbitrarily.
回答2:
You can just search all cultures by 2-letter code:
CultureInfo.GetCultures(CultureTypes.AllCultures)
.Where(cu => cu.TwoLetterISOLanguageName == code);
Just note that there may be multiple results.
来源:https://stackoverflow.com/questions/45884544/2-letter-iso-country-code-to-cultureinfo