解析来自不同文化背景的数字在C# [英] Parsing numbers from different cultures in C#

查看:206
本文介绍了解析来自不同文化背景的数字在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一些代码字符串解析为一个双,但是这个字符串传递给我从另一台机器。自然的问题已经出现,其中培养可以是不同的。所以,虽然机器A可以给我:

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 different. So, while machine A might send me:

"0.5"

机b可能给我

"0,6"

由于它在德国,拥有不同的文化。

Because it's in Germany and has a different culture.

什么是正确解析这两个输入的最佳方式?使用 CultureInfo.InvariantCulture 作为参数传递给 Convert.ToDouble 有人建议,但不会只帮助其中生产上述字符串,而不是别人的时候可以给我不同的?

What's the best way to correctly parse both of these inputs? Someone suggested using CultureInfo.InvariantCulture as an argument to Convert.ToDouble but won't that only help where I'm producing the above strings, not when someone else can send me different ones?

我是正确的思维,我需要知道源文化变革 Thread.CurrentThread.CurrentCulture 来尝试转换之前搭配?

Am I right in thinking I'll need to know the source culture and change Thread.CurrentThread.CurrentCulture to match before attempting to convert?

推荐答案

它是一台机器,或者是发送此人?如果它是一个机器 - 这就是说,有一个决定哪些数据要发送,而不是它是用户输入的盲传输另一台机器上的应用程序,那么对于这样的事情的格式应而指定了区域设置相关。一般来说,这意味着你们都同意使用 CultureInfo.InvariantCulture 或文化等同于如果其他应用程序不是.NET。

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.

如果它是一个人,你知道他们的语言环境,那么你可以使用 double.Parse(decString,CultureInfo的)。这可以失败,如果如一些讲英语的人借用自己的德语朋友的电脑。

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.

如果您知道不会有任何分组分隔符(如123,456.78或123' 457,78),那么你可以使用 double.Parse(decString.Replace('',''),CultureInfo.InvariantCulture),但不能如果有分组为这意味着 123,456.78 变成 123.456.78

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.

这篇关于解析来自不同文化背景的数字在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆