Convert a csv generated list string to a float

+2 Chris Blum · September 16, 2014
I'm having trouble working with some numbers from a csv file.
I can print the string value to console easily.
However, I wanted to use some of the numbers for calculations and need to convert them to a float.

First I tried just storing the values as a float in my list but it didn't work. (Probably because there are some null values).
I can't just ignore the value if it's null because I need to keep all my records in order.
For example,
studentList[I] needs to be equal to ipHoursList[I]. If I ignore some values, they won't line up and my data won't be useful.

I may add an if statement where if the value is null I instead save a 0 value.

However, I thought I might just convert all the string values from my list to a float.

for(int i = 0; i < stringList.Count; i++){

if (floatHolder != null && floatHolder != 0 && studentNameList == "student name")

floatHolder = float.Parse(stringList);




This text is only printing 0 over and over. If I write line directly from the stringList[I] I get the true values, 1.2, .6, etc.
The purpose of this is to add the values to generate a graph of their time spent compared to the time the syllabus wants them to spend.
I'll be using some code similar to this.

float floatHolder = 0;

for(int i = 0; i < stringList.Count; i++){

if (floatHolder != null && floatHolder != 0 && studentNameList == "student name")

floatHolder = float.Parse(stringList + floatHolder);




This will keep a running total of hours spent as each lesson is iterated and it will plot a point on a graph.
Long story short, how can I take a single element of a List<string> and turn it into a float.
What are some things I need to watch out for (null values, etc.)
Thank you!

Post a Reply


Oldest  Newest  Rating
0 Chris Blum · September 18, 2014
It's a work in progress. The specific error I mentioned in the title of this post was fixed by checking for "" instead of null.
Now I need to think of a creative way to automatically span my X axis based on the number of lessons the student has taken without losing my x axis labels.

I didn't have any time to work on it yesterday, was busy setting up new workstations, fixing an issue with backup exec and knocked out another 10 tickets or so.

Thanks for asking, i'll post on here when I'm working on the next section

Next step.
Students may attempt the same lesson multiple times but they way I'm plotting my graph isn't taking that into account. I need to make 1 point per x axis label and have the total flight hours for each lesson accumulated. I have an idea how to do this but it seems like a lot of manual code input instead of simple loops iterating a list.

Maybe a loop with a case statement inside that performs an action based on lesson name. Only thing is we have over 30 courses, each with 20+ lessons and I don't enjoy writing all that code manually. I'll update when I've got some progress and maybe you can check it out and see what you think.
+1 Eugene Botma · September 18, 2014
So did you fix get it working properly?
0 Chris Blum · September 16, 2014
**Prenote - I am going to remote log into my work station to grab more details to fill out this post. Exact details will be provided within 30 minutes of this post.**
**Edit - I've added the actual code I'm running in my chartTest program as well as the errors I'm getting**

Our company works with an offsite vendor which stores activities for our flight students (I work for a flight school).
Our instructor pilots want to analyze the data to see if our students are on track to graduate on time.
The offsite vendor generates reports for us from their internal oracle database.
I download a report as a csv and then capture each column in a list<string>.
This has seperated each "activity" in different lists that are all linked together by their location in the list. ie list.

Student name | Lesson # | Instructor | Lesson Date     | Grade    | Flight Hours  | etc. etc. I have about 30 lists in my master program.
John                        2             Jerry             Today            Fail              1.4
Stu                          3              Bob           Yesterday         Pass            1.1

So when I take the 0 element, all of those elements apply to that lesson taken by John. I've checked my method for importing and all my lists have the same number of elements and have accurate data.

In my master program (I say master program because I test all the different modules to verify they work before adding them into my main project, so I have a chart program, an import program, etc.), all of my lists, strings, buttons have a naming convention which tries to accurately name exactly the information and tool i'm using.
listStudentName, listLessonNumber, listInstructor.
buttonInitializeData, buttonCreateCharts, buttonClearCharts.

The importing works fine with List<string> listFlightHours = new List<string>();
When I try List<float> listFlightHours = new List<float>(); I get import errors. I haven't tested if a blank value is giving me the error but I need to test it. If it is, I may try running an if statement to replace the null with a 0.0.

I was having a similar issue when running an if statement to only pull information for a given student, or student & course. I found a fix by simply storing the element from my list as a single string
//I convert the text from a combo box to an object, then to a string for comparision in an if statem//-ent later
Object studentNameObject = comboBoxStudentName.SelectedItem;
String studentNameString = studentNameObject.ToString();
Object courseNameObject = comboBoxCourseName.SelectedItem;
String courseNameString = courseNameObject.ToString();

//Grab Data for specific student
for(var i = 0; i < Variables.listLessonDate.Count; i++){
string nameCheck = Variables.listStudentName;//Convert single list<string> element to a string
string courseCheck = Variables.listCourseName;

//Critera pulled from comboBox on the main form to narrow data displayed
 if(nameCheck == studentNameString && courseCheck == courseNameString && Variables.listGrade == "S"){
richTextBoxStudentInformation.AppendText(Variables.listLessonStatus + "\t| " + Variables.listLessonName + "\t| " + Variables.listLessonDate + "\t| " + Variables.listGrade + "\n");
textBoxInstructorName.Text = Variables.listInstructorName;
textBoxTeamName.Text = Variables.listTeamName;
textBoxGroupName.Text = Variables.listGroupName;
}//End if statement
}//End For statement

That is probably where the confusion is coming in with my code I posted and String nameHolder.
However, even when parsing a single string item into a float I was still getting an error. I was doing this inside of a loop though so i'm not sure if strings with a value are also causing the exception.

Here is the latest code I've tested from my chartTesting program.
//Inside a class called Variables which will make the variables global
public static List<string> listIPHours = new List<string>();

//Reader to get data into my lists
var reader = new StreamReader(File.OpenRead(@"H:\testcsv.csv"));//create a stream reader object
while (!reader.EndOfStream)//Read complete csv file and store values
var line = reader.ReadLine();//import data to the stream
var values = line.Split(',');//splits strings seperated by commas
Variables.listIPHours.Add(values[49]);//Stores values from the 49th column of csv
}//End of While Loop

Series S1 = new Series();
float placeHolder = 0;
String stringPlaceHolder = "";
float listPlaceHolder = 0;
for (int i = 0; i < Variables.listIPHours.Count; i++) {
//String studentNameString = studentNameObject.ToString(); //This didn't work
if (Variables.listIPHours != null)//If statement for testing non-null values
stringPlaceHolder = Variables.listIPHours;//Convert List<string> into single string
listPlaceHolder = float.Parse(stringPlaceHolder);//Convert single string value to float
placeHolder = listPlaceHolder + placeHolder;//This allows me to plot each graph point with the total
//hours for each given lesson. It adds all the lessons until this point for a total flight hours.
S1.Points.AddXY(i, placeHolder);//plot x and y on the graph

Sorry about the code in my initial post. I was doing it from memory and it wasn't accurate.
The line that gives the error is

listPlaceHolder = float.Parse(stringPlaceHolder);

The error I get is, "Input string was not in a correct format".
Thanks again for your time and help.

I will take your suggestion of making a class to store the data and test it out. I'm also going to test adding 0 to null values and see if that works.

I got rid of the error by changing the code to this.
Series S1 = new Series();
float placeHolder = 0;
String stringPlaceHolder = "";
float listPlaceHolder = 0;
int nullHolder = 0;
for (int i = 0; i < Variables.listIPHours.Count; i++) {
//String studentNameString = studentNameObject.ToString();
if(Variables.listIPHours == ""){
Variables.listIPHours = nullHolder.ToString();
stringPlaceHolder = Variables.listIPHours;
listPlaceHolder = float.Parse(stringPlaceHolder);
placeHolder = listPlaceHolder + placeHolder;
S1.Points.AddXY(i, placeHolder);

+1 Eugene Botma · September 16, 2014
In any kind of storage system (like databases and csvs), storing null's are generally frowned upon and considered bad practice.

I'm a bit confused by your code though....

is stringList a list<string>, string[] or string?
same for studentNameList.

If stringList is anything other than a string, float.Parse(stringList); is going to give a syntax error.

floatHolder = float.Parse(stringList + floatHolder); 

this line also makes no sense.... a string +float = string concatenated with the string of said float.


string stringList = "100";
float floatHolder = 0;
floatHolder = float.Parse(stringList + floatHolder); 


//output is going to be:

Long story short:
for (int i=0; i < ActualListOfStrings; i++)
float tempfloat = float.Parse(ActualListOfStrings);
//do whatever you need with the float here

What can you do about nulls: don't have nulls. but if you must have, you can try:

for (int i=0; i < ActualListOfStrings; i++)
float tempfloat = 0;
if (float.TryParse(ActualListOfStrings, out tempfloat))
//this will be executed if the value was successfully parsed. tempfloat will have the parsed value.
//this will execute if the value was not parsed. tempfloat will still be 0.

From what i can gather, your going to have a lot of data that is relevant to each other, for example a student is enrolled in different classes, each class has a recommended amount of hours and a student has an actual amount of hours per class (incremented in segments). It would (imo) be best to create classes to accommodate this and thus group the relevant data. It would be easier to manage and work with.
  • 1



C# is an object-oriented language designed for improving the development of web applications.