Unable to insert decimal to sql server table through c# code

Sree picture Sree · May 2, 2011 · Viewed 10.7k times · Source

I'm not able to insert decimal values into Sql Server table.

What i'm trying to do is self explanatory through these lines of code:

long fileSizeInBytes = ComponentUploadControl.FileContent.Length;
Decimal fileSizeInMB = Convert.ToDecimal(fileSizeInBytes) / (1024.0m * 1024.0m);
Decimal fileSizeInMBRounded = Math.Round(fileSizeInMB, 2);
cmd.Parameters.Add("@fileSize", SqlDbType.Decimal).Value = fileSizeInMBRounded;

The value that is getting inserted into database is stripped of the decimal places. To be more specific if the fileSizeInMBRounded is 11.73, the value that is getting inserted into database is 11,00

Please help me

Thanks in anticipation

Answer

pseudocoder picture pseudocoder · May 2, 2011

My suspicion is that your decimal field is set up wrong in SQL. What you want is a decimal(18,2) field which allows for 2 decimal places. My suspicion is that you declared the field as decimal(18,0) (the default), which does not allow for any decimal places.

If you can use SQL Server Profiler to verify the contents of the INSERT going to your DB, it would be easier for you to determine whether a problem like this is due to your code or something on the SQL server.