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

前端 未结 2 921
执笔经年
执笔经年 2021-01-22 17:04

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

相关标签:
2条回答
  • 2021-01-22 17:12

    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

    0 讨论(0)
  • 2021-01-22 17:29

    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

    0 讨论(0)
提交回复
热议问题