Attention: We are retiring the ASP.NET Community Blogs. Learn more >

NumberFormatInfo

I was recently confronted with this problem:

  • Read and parse a file with numbers having a dot as a decimal separator.
  • Parse the info no matter what culture the user is.
  • Don’t affect the current culture.

So here in Quebec, many users are using the "fr-CA" culture that has a comma as the decimal separator.  What I would usually do is to change the current culture like this:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

The downside is that it affects the strings stored in resources files that are displayed to the users.  I don’t want to display "en-US" strings to every users. The ideal way would be to specify that a dot is the decimal separator only for specific lines of code.  Here’s how to do it with NumberFormatInfo object:

You new a NumberFormatInfo object with the current culture number formatting information and you change the NumberDecimalSeparator to a dot.  You then use the object as a parameter for parsing methods.

NumberFormatInfo nfi = new CultureInfo(Thread.CurrentThread.CurrentCulture.LCID, false).NumberFormat;
nfi.NumberDecimalSeparator = ".";
decimal zeeNomebeurre;
string zeeStringue = "2.01";
zeeNomebeurre = decimal.Parse(zeeStringue, nfi);

That's one way to do it but one way I never used before.

1 Comment

Comments have been disabled for this content.