views:

54

answers:

3

I'm using English Visual Studio 2008 on English Windows 7, but I'm based in the Netherlands. A lot of my programs need to read and write floating point numbers. Compared to English, the Dutch notation of numbers switches the meaning of dots and comma's (i.e. 1.001 in Dutch is a thousand and one, and 1,001 is 1 + 1/1000). I will never ever ever have to write (or read) numbers in Dutch format, but for some reason, every program I compile defaults to it, so every ToString() is wrong. This gets me every time. I know I can put this at the start of every thread:

System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

Or replace every instance of ToString() with:

String.Format(CultureInfo.InvariantCulture, "{0:0.####},{1:0.####}", x)

But sometimes I just want to compile something to see how it works, and not make any changes. Also, I'm bound to forget about this sometimes. Is there no way to just tell C#, .NET and/or Visual Studio to just always make all my projects/programs use the English number format?

+1  A: 

You can add a line that sets CurrentCulture to Program.cs in your project templates.

SLaks
+4  A: 

It's not a matter of compilation - it's a matter of what happens at execution time. Unless you explicitly specify a culture, the current culture (at execution time) will be used. There's no way of changing this behaviour that I'm aware of, which leaves you the options of:

  • Explicitly stating the culture to use
  • Explicitly changing the current culture

Note that even if you change the current culture of the current thread, that may not affect things like the thread pool. Personally I think it's better to always use the culture explicitly.

You could always write your own extension methods to (say) call the original version but passing in CultureInfo.InvariantCulture. For example:

public string ToInvariantString(this IFormattable source, string format)
{
    return source.Format(format, CultureInfo.InvariantCulture);
}

Getting that right everywhere could be a pain, admittedly... and to avoid boxing you'd actually want a slightly different signature:

public string ToInvariantString<T>(this T source, string format)
    where T : IFormattable
{
    return source.Format(format, CultureInfo.InvariantCulture);
}
Jon Skeet
A: 

Try: Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

Andriy Shvay