Nieprawidłowy format ciągu wyjściowego

0

Napisałam program który porównuje dwa pliki .csv najpierw sprawdza towary po symbolu czy się zgadzają a następnie ceny.. Niektóre ceny mam z przecinkiem więc przekonwertowałam dane z pliku, ceny na float.. Dostaje komunikat "Nieprawidłowy format ciągu wyjściowego" ? Pytanie co robię źle?

class Program
    {

        static void Main(string[] args)
        {
            string strFilePath = @".csv";
            string strFilePath1 = @".csv";
            string strFilePath2 = @".csv";
            DataTable towary = ConvertCSVtoDataTable(strFilePath);
            DataTable towary1 = ConvertCSVtoDataTable1(strFilePath1);
            DataTable towary2 = new DataTable(strFilePath2);
            //Console.WriteLine("Liczba wczytanych rekordów: " + towary.Rows.Count);
            

            using (StreamWriter str = new StreamWriter((strFilePath2), true, Encoding.GetEncoding(1252)))
            {
                str.WriteLine(@"Symbol;Nazwa;CenaNetto1;CenaNetto2");
            }
            try
            {
                
                for (int i = 0; i < towary.Rows.Count; i++)
                    for (int y = 0; y < towary1.Rows.Count; y++)
                    {
                        {
                            
                            float a = float.Parse(towary.Rows[i]["CenaNetto1"].ToString());  //W tym miejscu pojawia się komunikat
                            float b = float.Parse(towary1.Rows[y]["CenaNetto1"].ToString());

                            if (towary.Rows[i]["Symbol"].Equals(towary1.Rows[y]["Symbol"]))
                                {
                                    Console.WriteLine("Sa równe" + towary.Rows[i]["Symbol"] + " " + towary1.Rows[y]["Symbol"]);

                                    if (a!=b)
                                    {
                                        string sym = Convert.ToString(towary.Rows[i]["Symbol"]);
                                        Console.WriteLine("Nie sa rowne, tabela1: " + towary.Rows[i]["CenaNetto1"] + "tabela2: " + towary1.Rows[y]["CenaNetto1"]);

                                        using (StreamWriter str = new StreamWriter((strFilePath2), true, Encoding.GetEncoding(1252)))
                                        {

                                            str.WriteLine(String.Format("{0}; {1}; {2}; {3}", towary.Rows[i]["Symbol"], towary.Rows[i]["Nazwa"], towary.Rows[i]["CenaNetto1"], towary1.Rows[y]["CenaNetto1"]));


                                            str.Close();
                                        }


                                    }
                                }
                            }
                        
                    }
            }
            catch (IOException e)
            {
                Console.WriteLine($"Wyjątki: '{e}'");

            }
            Console.ReadKey(true);
        }
    
        public static DataTable ConvertCSVtoDataTable(string strFilePath)
        {
            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(';');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                   

                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(';');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    
                    dt.Rows.Add(dr);
                }

            }


            return dt;
        }

        public static DataTable ConvertCSVtoDataTable1(string strFilePath1)
        {
            DataTable dt1 = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath1))
            {
                string[] headers = sr.ReadLine().Split(';');
                foreach (string header in headers)
                {
                    dt1.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(';');
                    DataRow dr = dt1.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt1.Rows.Add(dr);
                }

            }
            return dt1;
        }
    }
}
0

Jaką masz pewność, że to towary.Rows[i]["CenaNetto1"] nie jest NULL. Po drugie, polecam to CsvHelper

0

Nieprawidłowo konwertujesz.

float a = float.Parse(towary.Rows[i]["CenaNetto1"].ToString()); - ten kod zakłada, że wartość zmiennoprzecinkowa reprezentowana jest zgodnie z ustawieniami aktualnego wątku, które pewnie tożsame są z ustawieniami komputera, więc np. dla en-us separatorem będzie kropka, a dla pl będzie nim przecinek.

0

Albo to co @WeiXiao wrzucił albo:

string test1 = "1,234";
string test2 = "1.234"; //Ten nie przejdzie. Musisz zrobić Replace() kropki na przecinek

float result1 = float.Parse(test1);
float result2 = float.Parse(test2.Replace(".",",")); // <-- W ten sposób przejdzie.

Bardzo popularny problem.

2

Raczej unikałbym replaców i faktycznie spróbował zrobić to dobrze.

Życzę zabawy z tym: 12,500.50 / 1,234,567.89 / 1.234.567,89 itd.

0

Zrobiłam to w ten sposób, możecie spojrzeć czy to ok bo w dalszym ciągu problem..

                            CultureInfo ci = (CultureInfo)CultureInfo.CurrentCulture.Clone();
                            ci.NumberFormat.CurrencyDecimalSeparator = ",";
                            float a = float.Parse(towary.Rows[i]["CenaNetto1"].ToString(), NumberStyles.Any, ci);
                            float b = float.Parse(towary1.Rows[y]["CenaNetto1"].ToString(), NumberStyles.Any, ci);
2

A nie wystarczy float.Parse(towary.Rows[i]["CenaNetto1"].ToString(), CultureInfo.InvariantCulture);?

(BTW, do parsowania plików CSV możesz zapoznać się ze świetną biblioteką CsvHelper)

0

Faktycznie mieliście racje wystarczyło skorzystać z biblioteki CsvHelper... Poszło szybko, sprawnie i bezbłędnie ;-)

1 użytkowników online, w tym zalogowanych: 0, gości: 1