Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I add value to SqlDataRecord number is rounding

Tags:

c#

sql-server

When I add a value to my SqlDataRecord some how it is round the value. I am not sure what is causing it.

EDIT: John made a good point Left out the property type for dm which is "decimal?"

TotalCount = 2.5245332200983

SqlDataRecord rec = new SqlDataRecord(
                new SqlMetaData("TotalCount", SqlDbType.Decimal));

rec.SetNullableDecimal(0,dm.TotalCount);

When it is written to the DB it is showing 3.0000000000000

Database Type added so I can pass a TVP:

CREATE TYPE dbo.TestCount AS TABLE(
TotalCounts decimal(38,20) NULL
);

Database Table:

CREATE TABLE dbo.TestCountTbl(
TotalCounts                 decimal(38,20) NULL);

What am I doing wrong? Is the SqlDbType wrong?

EDIT: Per @user957902 I had to add precision / scale to my SqlDataRecord....totally makes sense...duh. So I added that and works like a charm. Thanks All!

SqlDataRecord rec = new SqlDataRecord(
                new SqlMetaData("TotalCount", SqlDbType.Decimal,38,20));
like image 639
scarpacci Avatar asked Dec 06 '11 22:12

scarpacci


1 Answers

According to the documentation for the SqlMetaData constructor you are using here, for SqlDbType.Decimal, the default for Precision is 18 and for scale is 0. So by default its not going to store anything past the decimal. You will need to use the constructor that allows you to set precision and scale descibed here.

public SqlMetaData(
    string name,
    SqlDbType dbType,
    byte precision,
    byte scale
)
like image 102
user957902 Avatar answered Nov 07 '22 08:11

user957902