C# 将任何格式字符串转换为双精度
我尝试搜索 google 和 stackoverflow 但没有成功。
我遇到“输入字符串格式不正确”的问题。我正在使用的应用程序除外。
问题是,我使用 doubleNumber.ToString("N2"); 将一些双精度值转换为字符串。以便将它们存储在 XML 文件中。当我切换测试机器时,存储在一台测试机器上的XML文件无法返回到双精度值。
我已经尝试了所有我能想到的解决方案,但是设置数字区域性不起作用,使用CultureInfo.InvariantCulture,替换字符也不起作用。有时这些值存储为“3,001,435.57”,有时(在其他 PC 上)存储为“3.001.435,57”。
无论输入格式是什么,是否有某种函数或方法可以从字符串中解析双精度值?
谢谢。
I tried searching google and stackoverflow without success.
I'm having a problem with "Input string was not in a correct format." exception with an application I'm working at.
Thing is, that I convert some double values to strings with doubleNumber.ToString("N2"); in order to store them in XML file. When I switch testing machines, XML file stored on one can't be returned back to double values.
I've tried all of the solutions I could think of, but setting number culture didn't work, using CultureInfo.InvariantCulture, replacing characters also doesn't work. Sometimes the values are stored like "3,001,435.57" and sometimes (on other PC) like "3.001.435,57".
Is there some function or a way to parse a double from string, whatever the input format is?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须指定区域性,因为(例如)“3,001”不明确 - 是 3.001 还是 3001?
根据您的数字的外观,也许您可以尝试通过计算
、
和.
字符的数量和/或检查它们的位置来检测区域性。You have to specify a culture because (eg.) "3,001" is ambiguous - is it 3.001 or 3001?
Depending on what your numbers look like, perhaps you could attempt to detect the culture by counting number of
,
and.
characters and/or checking their positions.这是您要查找的内容...
http://msdn.microsoft.com /en-us/library/9s9ak971.aspx
这将接受一个字符串变量和一个格式提供程序。您需要创建一个格式提供程序来提供您要转换的文化信息。
Here is what you are looking for...
http://msdn.microsoft.com/en-us/library/9s9ak971.aspx
This will accept a string variable and a format provider. You need to create a format provider that provides the culture information you are looking to convert out of.