Parsing numbers from different cultures in C#

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

提交回复
热议问题