0

Having a lot of trouble getting a program to insert the actual number without any imprecision from C# to SQL server.

For example, here is the code for how the data is handled in C# before pushing to the SQL Server:

DataTable dt = new DataTable();
dt.Columns.Add("Number", typeof(double));

dt.Rows.Add(6.5);
dt.Rows.Add(7);
dt.Rows.Add(8);

SqlConnection con;
string sqlCmd;
SqlCommand cmd;

using (con = new SqlConnection(Common.DBLink))
{
                con.Open();
                SqlBulkCopy bulkCopy = new SqlBulkCopy(con);
                bulkCopy.DestinationTableName = "NumberTable";
                bulkCopy.WriteToServer(dt);
                con.Close();
}

But if I have a number like 2.85 in there, it gets inserted as 2.8499. The SQL column is a DECIMAL(10,4) datatype. This only happens for very few numbers. It never happens for values like 12.5 or 20.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
eek
  • 688
  • 2
  • 21
  • 32
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Dec 10 '14 at 02:18
  • 2
    Note for the future. "double" and "decimal" are not spelled the same. Chances are they're different things. You will find this applies to many more pairs of "things" in your life: if they were the same thing, they'd likely be spelled the same. – John Saunders Dec 10 '14 at 02:43

1 Answers1

5

If you need a decimal value, don't store it as a double in your DataTable.

Change your column type to a decimal and try it again:

dt.Columns.Add("Number", typeof(decimal));

You can find a lot of helpful information by searching for "c# double vs decimal", such as this SO post, or Jon Skeet's articles on Decimals and Doubles.

Community
  • 1
  • 1
Grant Winney
  • 65,241
  • 13
  • 115
  • 165