Can I set the decimal symbol to use everywhere in my application

扶醉桌前 提交于 2019-12-31 03:47:09

问题


I tracked down a bug in my application that occurred for people in countries where the default decimal symbol was a comma instead of a period. Is there any way in C# to set the decimal symbol for my application without affecting other apps or permanently changing the system settings? I tried this but it says the NumberDecimalSeparator is readonly.

Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";

回答1:


I you still need to do that you can change the CurrentCulture on the thread like so:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-Us");

Chooe a Culture that has the decimal properties you need.

var numpre = 1.1.ToString();
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-Us");
var numpost = 1.1.ToString();
numpre.Dump();
numpost.Dump();

Output:

1,1
1.1




回答2:


Depending on the situation, the right thing to do may not be to try to enforce a format, but to make your application aware of the locale and take it into account. Which is something really easy to do since .NET has it all implemented already (otherwise it would be a nightmare).

I'd say there are two cases to treat: when data can be passed from one machine to another (some stored data, a file, a script, etc.), and when it is not supposed to (a visual feedback, a value field, etc.).

When it's about data that can be passed from one machine to another, you have to choose a format that is culture agnostic. This will guarantee the machines use the same format and interpret a given data the same way regardless of the machine user settings. That's what programming languages do, and seems to be your case.

The .NET library provides CultureInfo.InvariantCulture for this:

double x = 0.0;
double.TryParse(source, NumberStyles.Float, CultureInfo.InvariantCulture, out x);
string str = x.ToString(CultureInfo.InvariantCulture);

When it's about local information, you should read and write in the language of the user, using his locale to parse numbers in inputs (text fields) and format them in outputs. This tends to be neglected, but I think it is a very important point, as a number like 1,234.567 will have a radically different meaning depending on the culture. See for example how a software like Microsoft Excel will represent and let you enter numbers differently depending on your environment settings.

In this case the above code snippet would become:

double x = 0.0;
double.TryParse(source, NumberStyles.Float, CultureInfo.CurrentUICulture, out x);
string str = x.ToString(CultureInfo.CurrentUICulture);

See more on the MSDN documentation: http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx



来源:https://stackoverflow.com/questions/17900164/can-i-set-the-decimal-symbol-to-use-everywhere-in-my-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!