将十进制数字从字符串转换为双精度 [英] Convert decimal numbers from string to double

查看:152
本文介绍了将十进制数字从字符串转换为双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将包含十进制数字的nig数字读取到一个字符串数组中,例如:10.4。我想获得一个双打数组。我的方法仅适用于不带小数部分的数字,但对于十进制的数字,则会出现以下错误:

I have read a file containnig numbers including decimal ones e.g.: 10.4 into an array of strings. 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:


类型为'System.FormatException的未处理的异常'发生在
mscorlib.dll中。附加信息:输入的字符串不是
正确格式。

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format.

应该您有一些想法如何修改代码以使其适用于所有正实数?

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();


推荐答案

您应该考虑语言环境设置。默认情况下,double.Parse与当前线程语言环境配合使用,该语言环境可能指定的十进制分隔符与文件中使用的十进制分隔符不同。例如。某些区域性使用逗号(,),而其他区域性使用句点(。)

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. E.g. 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();

这篇关于将十进制数字从字符串转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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