eek
eek

Reputation: 724

Inserting double into SQL Server 2012 Decimal column leads to imprecision

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.

Upvotes: 0

Views: 1548

Answers (1)

Grant Winney
Grant Winney

Reputation: 66449

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.

Upvotes: 5

Related Questions