简体   繁体   中英

Converting entire string array to double array throws input format exception, but converting single elements works fine

I'm trying to convert a string array (which I populated from a .txt file) to a double array in C#.

This is what I've tried, using a for loop, which I've seen on other solutions.

            string[] StringArr = File.ReadAllLines("256.txt");

            double[] DoubleArr = new double[StringArr.Length];

            for(int i = 0; i < StringArr.Length; i++)
            {
                DoubleArr[i] = Convert.ToDouble(StringArr[i]);
            }

This threw the exception "System.FormatException: 'Input string was not in a correct format." for

DoubleArr[i] = Convert.ToDouble(StringArr[i]);

I thought there was something wrong with the format of the data from the text file, but when I tried

DoubleArr[0] = Convert.ToDouble(StringArr[0]);
Console.WriteLine(DoubleArr[0]);

this worked without throwing an exception, and printed the correct number.

I assume that I must have done something wrong with the for loop?

without seing your data, you could have a problem of Incorrect decimal separator

Different cultures use different decimal separators ( , and . for example)

If you replace . with , all will be okay

or you use the Culture :

double.Parse("12.345", System.Globalization.CultureInfo.InvariantCulture)

also, you could have an empty value which is an incorrect double

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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