简体   繁体   English

尝试将字符串解析为double,得到“输入字符串格式不正确”。

[英]Trying to parse a string to a double, getting “Input string was not in a correct format.”

I need to parse a string from a datatable into a double. 我需要将数据表中的字符串解析为double。 I have a datatable (dt) and it has different columns, and each of these columns are converted to strings with the .ToString() method. 我有一个数据表(dt),它有不同的列,每个列都使用.ToString()方法转换为字符串。 However, when I try to output the latitude and longitude of the data, I get an error "Input string was not in a correct format." 但是,当我尝试输出数据的纬度和经度时,我收到错误“输入字符串格式不正确”。 So I guess my main question is, how do you parse text from an object converted to a string using the .ToString() method.. 所以我想我的主要问题是,如何使用.ToString()方法解析转换为字符串的对象中的文本。

using System;
using System.IO;
using System.Collections;
using System.Data;

namespace SalesMap
{
    class SalesMap
    {
        private static DataTable InitData1()
        {
            //Datatable for entire list of zipcodes
            DataTable datat = new DataTable("DATA");
            DataColumn state = new DataColumn();
            DataColumn county = new DataColumn();
            DataColumn statecounty = new DataColumn();
            DataColumn latitude = new DataColumn();
            DataColumn longitude = new DataColumn();
            DataColumn salesperson = new DataColumn();

            //Add the columns to the datatable
            datat.Columns.Add(state);
            datat.Columns.Add(county);
            datat.Columns.Add(statecounty);
            datat.Columns.Add(latitude);
            datat.Columns.Add(longitude);
            datat.Columns.Add(salesperson);

            return datat;
        }       

        private static String InitPath()
        {
            string path = "C:/Documents and Settings/Andre/Desktop/salesmapdata/MapPointCountyLatLong.csv";
            return path;
        }

        public static void Main()
        {
            try
            {
                DataTable dt = InitData1();
                StreamReader sr = new StreamReader(InitPath());
                String csvData = string.Empty;

                while ((csvData = sr.ReadLine()) != null)
                {
                    String[] data = csvData.Split(',');
                    //dt.Rows.Add(data);
                    DataRow newRow1 = dt.NewRow();
                    newRow1[0] = data[0].ToString(); //state
                    newRow1[1] = data[1].ToString(); //county
                    newRow1[2] = data[2].ToString(); //state|county
                    newRow1[3] = data[3].ToString(); //latitude
                    newRow1[4] = data[4].ToString(); //longitude
                    newRow1[5] = data[5].ToString(); //salesperson
                    dt.Rows.Add(newRow1);

                    Console.WriteLine("Row added for: dt");
                }

                foreach (DataRow row1 in dt.Rows)
                {
                    double latitude1 = Double.Parse(row1[3].ToString());
                    double longitude1 = Double.Parse(row1[4].ToString());

                    if (row1[5].ToString() != "UNKNOWN" || row1[5].ToString() != "SALESMAN")
                    {
                        Console.WriteLine(latitude1);
                        Console.WriteLine(longitude1);
                    }
                }

                dt.WriteXml(@"c:\test\dt1.xml");
                sr.Close();
            }

            catch (Exception e)
            {
                StreamWriter sw = new StreamWriter(@"c:\test\error.txt");
                sw.WriteLine(e.Message.ToString());
                sw.Close();
            }
        }
    }
}

First of all, when reading data from CSV file, you don't need to call data[x].ToString() on each array element, since they are already strings. 首先,当从CSV文件读取数据时,您不需要在每个数组元素上调用data[x].ToString() ,因为它们已经是字符串。

Few potential issues you might have with Double.Parse calls: Double.Parse调用可能存在的几个潜在问题:

  1. The data in your CSV file is really in the wrong format (maybe you misplaced the column numbers, or data might have an additional symbols that couldn't be parsed, like Tim mentioned in his comment). 您的CSV文件中的数据实际上格式错误(可能您错放了列号,或者数据可能有一些无法解析的其他符号,如Tim在评论中提到的)。
  2. You have empty strings in your columns. 列中有空字符串。 Those cannot be parsed to double. 那些无法解析为加倍。 You need to check that first, using string.IsNullOrWhitespace() or something similar. 您需要首先检查,使用string.IsNullOrWhitespace()或类似的东西。
  3. Your culture is wrong. 你的文化错了。 You might have latitude and longitude values that use decimal point in your CSV file, but your current thread culture might be using comma as decimal separator. 您可能在CSV文件中使用小数点的纬度和经度值,但您当前的线程文化可能使用逗号作为小数点分隔符。 There's an overload of Decimal.Parse() that accepts Culture as parameter (you could supply CultureInfo.InvariantCulture or any other CultureInfo ). Decimal.Parse()重载接受Culture作为参数(您可以提供CultureInfo.InvariantCulture或任何其他CultureInfo )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM