C# .NET - how to insert decimal values into database

Asked By abinav shankar on 01-Feb-12 05:08 AM

Hi

I am sending the value for number of days as float from the code behind(c#) and the datatype for number of days in the table is decimal(2.1) but when i send 0.5 as the number of days it is getting saved as 1 into the database how to proceed

kalpana aparnathi replied to abinav shankar on 01-Feb-12 05:16 AM
hi,

Try this

INSERT INTO MyTable (myDecimal) VALUES ( 1.1 )
D Company replied to abinav shankar on 01-Feb-12 05:40 AM
Hello Friend.

Float is Approximate-number data type, which means that not all values in the data type range can be represented exactly.
Decimal/Numeric is Fixed-Precision data type, which means that all the values in the data type reane can be represented exactly with precision and scale.
 

Converting from Decimal or Numeric to float can cause some loss of precision. For the Decimal or Numeric data types, SQL Server considers each specific combination of precision and scale as a different data type. DECIMAL(2,2) and DECIMAL(2,4) are different data types.

This means that 11.22 and 11.2222 are different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222 are same data types.



Hope it helps!!!
Regards
D
Reena Jain replied to abinav shankar on 01-Feb-12 06:35 AM
HI,

Might 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.