11.6 Formatting Numbers Correctly Based on Culture You want to ensure that you correctly format any numbers that are displayed to a user based on her culture. | Technique Numbers can be formatted by objects that support the IFormatProvider interface. For applications that need to display numbers in different cultures other than the current culture, create a new CultureInfo object and pass the NumberFormatInfo property as the IFormatProvider parameter. For instance, to display a number with thousands and decimal separators based on a given culture, the code appears as follows : private void numericUpDown1_ValueChanged(object sender, System.EventArgs e) { // demonstrates formatting a value using correct // culture number format cbLanguage is a combobox // containing specific cultures using ISO identifiers NumberFormatInfo currentNFI = new CultureInfo( cbLanguage.SelectedItem.ToString(), false ).NumberFormat; lblUpDown.Text = numericUpDown1.Value.ToString("N", currentNFI); } Comments Various methods within the .NET Framework such as ToString and Parse allow you to specify how formatting should be performed by using an object that implements the IFormatProvider interface. For numerical data, the NumberFormatInfo object defined within a CultureInfo object allows you to format a number correctly for a given culture. By default, you might find that you really never need to pass an IFormatProvider to these methods. If you do not specify a format provider, the default provider for the CurrentCulture is used. For instance, if you remove the currentNFI parameter in the ToString method shown earlier, the number is formatted correctly on a German system and likewise for a user running on an English install. |