简体   繁体   中英

How to make C# write English (non-localized) number format by default?

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 (ie 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?

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 static 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 static string ToInvariantString<T>(this T source, string format)
    where T : IFormattable
{
    return source.Format(format, CultureInfo.InvariantCulture);
}

您可以在项目模板中添加一行,将CurrentCulture设置为Program.cs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM