-3

I am trying to read a csv file in to an data structure but I can't seem to convert it in to an double type.

static void Main(string[] args)
        {
            var reader = new StreamReader(File.OpenRead(@"E:\file.csv"));
            List<Double> close = new List<Double>();

            int counter = 0;


            while (!reader.EndOfStream)
            {
                counter = counter + 1;
                var line = reader.ReadLine();
                var values = line.Split(',');


                string str = values[4];
                Double val = Convert.ToDouble(str); //THIS IS THE PROBLEM

                Console.WriteLine(values[4].GetType());
            }

            // Prompt to Exit
            Console.WriteLine("Press any key to exit.");
            Console.Read();


        }

I get an error:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

values[4] is of type System.string

user1234440
  • 22,521
  • 18
  • 61
  • 103
  • Try this to parse `double.Parse(str,NumberStyles.Any, CultureInfo.InvariantCulture)` – Giorgos Betsos Jan 30 '15 at 19:17
  • what does values[4] contain, have you looked? – pm100 Jan 30 '15 at 19:17
  • Well if you get a `FormatException`, the obvious question is: what is the value that's causing it to throw the exception? – mason Jan 30 '15 at 19:17
  • possible duplicate of [Best way to parse command line arguments in C#?](http://stackoverflow.com/questions/491595/best-way-to-parse-command-line-arguments-in-c) – user1234440 Jan 30 '15 at 19:23
  • 1
    @user1234440 Why did you post that? This has nothing to do with parsing command line arguments. Update your question to include the value of `values[4]`. – mason Jan 30 '15 at 19:48
  • Sorry guys, I found the problem. It was because I had a header. I just needed to skip the header and it worked. Thanks for all the help. – user1234440 Jan 30 '15 at 19:51

2 Answers2

1

'System.FormatException' indicates a run-time issue caused by the data in your CSV file, not by the code of your program.

It means that the item at index four does not represent a valid double value. For example, it could be an empty string, or some other non-numeric string. In order to diagnose this problem properly, add a try/catch around the call of Convert.ToDouble(str), and print the message when you get an exception:

Double val;
try {
    val = Convert.ToDouble(str);
} catch (FormatException fe) {
    Console.Error.WriteLine("Got {0} when processing '{1}'", fe.Message, str);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Use the Double.Parse method. You can then provide NumberStyles corresponding to what's written in your .csv.

Laurent Jalbert Simard
  • 5,949
  • 1
  • 28
  • 36