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

走远了吗. 提交于 2019-12-02 01:39:25

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

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

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