Convert decimal numbers from string to double

2019-09-17 22:29发布

问题:

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:

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

回答1:

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


回答2:

Most likely this is a culture issue.Use InvariantCulture for parsing. Your numbers has dot (.) has decimal operator which is different than the decimal separator of your current culture.

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


标签: c# string double