简体   繁体   中英

2 Letter ISO Country Code to CultureInfo

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM