opticon
opticon

Reputation: 3594

TextFieldParser adding zeros to number in CSV

I'm using TextFieldParser to read a CSV file. This particular column in the CSV contains numbers: 3.14, 2.65, etc. I'm reading them as such:

        var path = @"C:\myfiles\file.csv";
        using (TextFieldParser csvParser = new TextFieldParser(path))
        {
            csvParser.SetDelimiters(new string[] { "," });                

            csvParser.ReadLine();

            var numbers = new string[5];
            numbers[0] = csvParser.ReadFields()[23];
            numbers[1] = csvParser.ReadFields()[23];
            numbers[2] = csvParser.ReadFields()[23];
            numbers[3] = csvParser.ReadFields()[23];
            numbers[4] = csvParser.ReadFields()[23];

            return numbers;
        }

This works, but the strings I'm getting back have two zeros appended; ie. 3.14 is returned as "3.1400". Is there a reason this is happening? A configuration option for the TextFieldParser, perhaps?

Upvotes: 0

Views: 336

Answers (3)

ArcherHero
ArcherHero

Reputation: 31

If you created the .csv file in excel, it's notorious for adding extra 0's and doesn't show them via their UI.

Try recreating your dataset in notepad or even better notepad++.

Upvotes: 0

AviFarah
AviFarah

Reputation: 337

My feeling is that the code works without the additional trailing "00". If you put a breakpoint at each of the numbers[x] you will find that it does not contain additional characters. My feeling is that your bug is elsewhere...

At least when I replicated your code in LINQPad, it did not produce the error that you describe...

Upvotes: 0

rweisse
rweisse

Reputation: 830

You could try to parse the returned strings to floats like this:

parseFloat(csvParser.ReadFields()[23]);

In this case you should change your array-type from string to number. Or generate a string again with toString()-Method after parsing it to float.

Upvotes: 1

Related Questions