#61 – Formatting and Parsing Strings for Non-Default Cultures

By default, when you convert a numeric data value to/from a string, the current culture is used.

The current culture dictates what characters to use for the thousands separator, decimal symbol, and the default formatting for date and time strings.  You can change the culture from the Formats tab in the Region and Language dialog in Control Panel.  (Windows 7).

Current culture typically matches the region that a user is located in.  It’s different from “UI culture”, which is the culture for the native language of the operating system.

You typically format output strings in the current culture and parse input strings based on the current culture.  But you can override this behavior and specify a culture to use.

 float f1 = float.Parse("4.5");   // Fails in regions that use ',' for decimal (e.g. France)
 float f2 = float.Parse("4.5", CultureInfo.InvariantCulture);    // Assume invariant (English), e.g. '.' for decimal

 // Display date/time using German culture
 Console.WriteLine(DateTime.Now.ToString(new CultureInfo("de-DE")));

Advertisements