0

I have a CSV file that consists of a long list of data where a row would for example look like this:

a, 8, c, d, "(1,000)"

Now I want to convert the last column into actual numbers so that I can multiply them by -1 and make them positive in the output file.

Here's part of my code:

calPlacehold = Int32.Parse(lineArr[4], NumberStyles.AllowThousands | NumberStyles.AllowParentheses);
if (calPlacehold < 0)
   {
      calPlacehold = calPlacehold * -1;
      lineArr[4] = calPlacehold.ToString();
   }
newLine = string.Join(",", lineArr);
writer.WriteLine(newLine);

I got a "input string was not in a correct format" error message. The problem might be that the commas are breaking the numbers apart so I added this line before the if statment to try to get them into the correct format.

lineArr[4] = lineArr[4].Replace(",", "");

However I still got the same error message, and when I checked the output csv file I noticed that all the commas still exist in the last column. The other parts of the code still work and the data is being updated correctly all excpet this part, and I don't understand why the Replace method isn't working.

Could anyone explain to me why the commas aren't getting replaced? Or if that's not the reason causing the format error, what is?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 1
    You should look at using TextFieldParser since you are dealing with commas inside CSV line. See here: https://stackoverflow.com/questions/6542996/how-to-split-csv-whose-columns-may-contain-comma. Than answer also contains a way to use a RegEx which may work as well. – dcp Apr 24 '23 at 14:57
  • 2
    Either `TextFieldParser` or CSVHelper is what you want. Don't try rolling your own parser it's a recipe for disaster – Charlieface Apr 24 '23 at 15:06
  • 2
    `lineArr[4]` likely contains the value `"(1` and `lineArr[5]` contains `000")`- assuming `string.Split(',' ...` created lineArr. You need more sophisticated parsing, that doesn't split the 5th column in two. – lidqy Apr 24 '23 at 15:28
  • Yes, I used the Split method to create lineArr. What I don't understand is the created array actually returns the value `"(1,000)"` correctly, but as soon as I try to int.parse it the commas break it apart. Thank you everyone for suggestions – NootNootNoob Apr 25 '23 at 00:23

0 Answers0