Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i create a new CultureInfo from a two-character language code?

Tags:

c#

cultureinfo

I need to format a number, based on a culture, but all I have is the Accept-Language from the HTTP request, which is a two-letter code like fr (for French)

Is this enough to create a CultureInfo that can handle numbers?

like image 795
Alexandru Pupsa Avatar asked Jan 30 '17 15:01

Alexandru Pupsa


1 Answers

This is a comment to illustrate the difference between neutral cultures and specific cultures:

var language = "fr";

var c1 = new CultureInfo(language);
Console.WriteLine(c1.EnglishName);              // "French"
Console.WriteLine(c1.IsNeutralCulture);         // "True"
Console.WriteLine((3.14m).ToString("C", c1));   // "3,14 €"

var c2 = CultureInfo.CreateSpecificCulture(language);
Console.WriteLine(c2.EnglishName);              // "French (France)"
Console.WriteLine(c2.IsNeutralCulture);         // "False"
Console.WriteLine((3.14m).ToString("C", c2));   // "3,14 €"

var languageAndCountry = "fr-CA";

var c3 = new CultureInfo(languageAndCountry);
Console.WriteLine(c3.EnglishName);              // "French (Canada)"
Console.WriteLine(c3.IsNeutralCulture);         // "False"
Console.WriteLine((3.14m).ToString("C", c3));   // "3,14 $"

In conclusion, if you have only the language, you cannot get everything. You can either get a neutral culture, or a "canonical" specific culture where some "typical" country is picked.

When you have both language and country, as in "fr-CA", things behave better.


On my system, the following specific cultures with "fr" exist:

fr-029, fr-BE, fr-BF, fr-BI, fr-BJ, fr-BL, fr-CA, fr-CD, fr-CF, fr-CG, fr-CH, fr-CI, fr-CM, fr-DJ, fr-DZ, fr-FR, fr-GA, fr-GF, fr-GN, fr-GP, fr-GQ, fr-HT, fr-KM, fr-LU, fr-MA, fr-MC, fr-MF, fr-MG, fr-ML, fr-MQ, fr-MR, fr-MU, fr-NC, fr-NE, fr-PF, fr-PM, fr-RE, fr-RW, fr-SC, fr-SN, fr-SY, fr-TD, fr-TG, fr-TN, fr-VU, fr-WF, fr-YT

(found with string.Join(", ", CultureInfo.GetCultures(CultureTypes.SpecificCultures).Where(x => x.TwoLetterISOLanguageName == "fr")))

like image 100
Jeppe Stig Nielsen Avatar answered Sep 30 '22 03:09

Jeppe Stig Nielsen