Parsing numbers from different cultures in C#

后端 未结 4 1605
滥情空心
滥情空心 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: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.

提交回复
热议问题