Display sample formats for different locales in C#


This example loops through the system’s defined locales and displays sample numbers, currency values, dates, and times in each.

When the program starts, the following code executes.

private void Form1_Load(object sender, EventArgs e)
    float float_value = 1234.56f;
    decimal dec_value = 1234.56m;
    DateTime now = DateTime.Now;

    // Loop through the locales.
    foreach (CultureInfo info in
        ListViewItem item = lvwResults.Items.Add(

        // You can't use a neutral culture as a format
        // provider, so if the CultureInfo is neutral,
        // look for a non-neutral ancestor.
        CultureInfo culture = info;
        while ((culture != null) && (culture.IsNeutralCulture))
            culture = culture.Parent;
        if (culture != null)
            item.SubItems.Add(float_value.ToString("N", culture));
            item.SubItems.Add(dec_value.ToString("C", culture));
            item.SubItems.Add(now.ToString("d", culture));
            item.SubItems.Add(now.ToString("t", culture));

This code first creates float, decimal, and DateTime sample values. It then loops through the CultureInfo objects returned by CultureInfo.GetCultures.

For each CultureInfo, the code adds the object’s English, native, and locale names to the ListView.

Next the code checks whether the object represents a neutral culture such as en. If it does, the object doesn’t contain information about a specific culture that is needed to format values. For example, the culture en doesn’t contain that information. In contrast, a specific culture such as en-US or en-GB.

If the object does represent a neutral culture, the code climbs up its parent hierarchy until it finds a non-neutral culture and it uses that one.

Having found a non-neutral culture, the program uses the culture to format float, decimal, date, and time values and adds them to the ListView.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in internationalization, localization and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.