简体   繁体   English

将十进制数字从字符串转换为双精度

[英]Convert decimal numbers from string to double

I have read a file containnig numbers including decimal ones eg: 10.4 into an array of strings. 我读了一个文件,其中包含nig数字,包括十进制数字,例如:10.4成字符串数组。 I want to obtain an array of doubles. 我想获得一个双打数组。 My method work for numbers without the decimal part only, but for decimal ones gives following error: 我的方法仅适用于不带小数部分的数字,但适用于十进制的数字会出现以下错误:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format. mscorlib.dll中发生了'System.FormatException'类型的未处理异常。其他信息:输入字符串的格式不正确。

Would you have some ideas how to modify the code to work for all positive real numbers? 您是否有一些想法,如何修改代码以使其适用于所有正实数?

string[] lines = System.IO.File.ReadAllLines(fd.FileName);
numbers_input = lines.Select(x => double.Parse(x)).ToArray();

You should be taking into account the locale settings. 您应该考虑到语言环境设置。 By default, double.Parse works with the current thread locale which may be specifying a different decimal separator than the one that was used in the file. 默认情况下,double.Parse与当前线程语言环境配合使用,该语言环境可能指定的十进制分隔符与文件中使用的十进制分隔符不同。 Eg some cultures use comma (,) while others use period (.) 例如,某些文化使用逗号(,),而其他文化使用句点(。)。

If your data file is fine and is using period as a decimal separator, then you can use 如果您的数据文件很好并且使用句点作为小数点分隔符,则可以使用

lines.Select(x => double.Parse(x, CultureInfo.InvariantCulture)).ToArray();

Most likely this is a culture issue.Use InvariantCulture for parsing. 这很可能是文化问题。使用InvariantCulture进行解析。 Your numbers has dot (.) has decimal operator which is different than the decimal separator of your current culture. 您的数字带有dot (。)的十进制运算符与当前区域性的十进制分隔符不同。

numbers_input = lines.Select(x => double.Parse(x, CultureInfo.InvariantCulture))
                     .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM