value getting changed during SqlBulkCopy

asp.net c# csv sqlbulkcopy sql-server

Question

I am trying to upload some data from csv file to sql server using SqlBulkCopy The problem here is that the values get changed automatically eg 0.9824 becomes 0.982400000095367

Here is the code that I am using

using (SqlBulkCopy bulkCopy = new SqlBulkCopy(strConnectionString, SqlBulkCopyOptions.FireTriggers))
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("dt", typeof(DateTime)));
            dt.Columns.Add(new DataColumn("wreb", typeof(string)));
            dt.Columns.Add(new DataColumn("zid", typeof(int)));
            dt.Columns.Add(new DataColumn("zone_name", typeof(string)));
            dt.Columns.Add(new DataColumn("region", typeof(string)));
            dt.Columns.Add(new DataColumn("iloss", typeof(float)));
            dt.Columns.Add(new DataColumn("dloss", typeof(float)));

            for (int i = 0; i < DataDS.Tables[0].Rows.Count; i++)
            {
                DataRow myDr = dt.NewRow();
                myDr["dt"] = DateTime.ParseExact(DataDS.Tables[0].Rows[i]["dt"].ToString(), "d/M/yyyy", null);
                myDr["wreb"] = DataDS.Tables[0].Rows[i]["wreb"].ToString();
                myDr["zid"] = DataDS.Tables[0].Rows[i]["zid"].ToString();
                myDr["zone_name"] = DataDS.Tables[0].Rows[i]["zone_name"].ToString();
                myDr["region"] = DataDS.Tables[0].Rows[i]["region"].ToString();
                myDr["iloss"] = DataDS.Tables[0].Rows[i]["iloss"].ToString();
                myDr["dloss"] = DataDS.Tables[0].Rows[i]["dloss"].ToString();
                dt.Rows.Add(myDr);
                myDr = null;
            }
            bulkCopy.BulkCopyTimeout = 0;
            bulkCopy.ColumnMappings.Add("dt", "Zdate");
            bulkCopy.ColumnMappings.Add("wreb", "Entity");
            bulkCopy.ColumnMappings.Add("zid", "ZoneID");
            bulkCopy.ColumnMappings.Add("zone_name", "Zone_Name");
            bulkCopy.ColumnMappings.Add("region", "region");
            bulkCopy.ColumnMappings.Add("iloss", "iloss");
            bulkCopy.ColumnMappings.Add("dloss", "dloss");
            bulkCopy.DestinationTableName = "tbl_zloss";
            bulkCopy.WriteToServer(dt);
        }

Accepted Answer

Looks like you're using float which is an imprecise datatype.
Use decimal to get exact values. Precision and scale depend on your data



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why