Parsing numbers from different cultures in C#

后端 未结 4 1603
滥情空心
滥情空心 2021-01-18 12:07

I\'m writing some code to parse a string into a double, but this string is passed to me from another machine. Naturally a problem has occurred where the culture may be diffe

相关标签:
4条回答
  • 2021-01-18 12:19

    Is it a machine or a person that's sending this? If it's a machine - that is to say, there's an application on another machine that decides what data to send rather than it being a "blind" transmission of user input, then the format for such things should be specified rather than locale-dependent. Generally this means you both agree to use CultureInfo.InvariantCulture or a culture equivalent to that if the other application is not .NET.

    If it's a person and you know their locale, then you can use double.Parse(decString, cultureInfo). This can fail if e.g some English-speaking person borrows their German-speaking friend's computer.

    If you know there won't be any grouping separators (e.g. 123,456.78 or 123'457,78) then you can use double.Parse(decString.Replace(',', '.'), CultureInfo.InvariantCulture) but can't if there's groupings as that means 123,456.78 becomes 123.456.78.

    0 讨论(0)
  • 2021-01-18 12:26

    Yes, to parse the numbers reliably you'll need to know the source culture.

    0 讨论(0)
  • 2021-01-18 12:28

    If you know the source culture, and can get a CultureInfo instance representing it, you can pass this to the Convert.ToDouble or Double.Parse method as a parameter. For instance, if you have this from a (known) German user:

    var cultureInfo = CultureInfo.GetCultureInfo("de-DE");
    double result = Double.Parse("0,5", cultureInfo);
    

    If you're not sure, but have a limited range of source cultures, then you could use a number of Double.TryParse attempts with the various cultures. However, as has been pointed out below, "1,000" could have quite different meanings depending on the culture...

    0 讨论(0)
  • 2021-01-18 12:30

    The best situation is when sender and receiver always use the same Culture for transmitting data. In your current case: even the german machine should send "0.5".

    The next best thing in theory, is to adjust the receiver's settings to conform to the sender's settings. Although in practice this is harder than the previous case: without the sender cooperation, it's impossible to exactly identify the culture. And when you can make the sender to cooperate, you are better off to force it into sending the culture you want. So you barely ever see this in practice.

    If you do NOT control the source, the only option left is trying to detect the culture, adjust your parsing, and hope it works. Expect it to be a constant source of bugs, though.


    So the best thing to do, is to settle on a culture (usually InvariantCulture) and adjust the sender. You will be better off in the long run.

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