Parsing numbers from different cultures in C#

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

提交回复
热议问题