views:

6708

answers:

7

Howdy, I have a DataRow pulled out of a DataTable from a DataSet. I am accessing a column that is defined in SQL as a float datatype. I am trying to assign that value to a local variable (c# float datatype) but am getting an InvalidCastExecption

DataRow exercise = _exerciseDataSet.Exercise.FindByExerciseID(65);
_AccelLimit = (float)exercise["DefaultAccelLimit"];

Now, playing around with this I did make it work but it did not make any sense and it didn't feel right.

_AccelLimit = (float)(double)exercise["DefaultAccelLimit"];

Can anyone explain what I am missing here?

+19  A: 

A SQL float is a double according to the documentation for SQLDbType.

Austin Salonen
+11  A: 

A float in SQL is a Double in the CLR (C#/VB). There's a table of SQL data types with the CLR equivalents on MSDN.

bdukes
+1  A: 

The float in Microsoft SQL Server is equivalent to a Double in C#. The reason for this is that a floating-point number can only approximate a decimal number, the precision of a floating-point number determines how accurately that number approximates a decimal number. The Double type represents a double-precision 64-bit floating-point number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, PositiveInfinity, NegativeInfinity, and Not-a-Number (NaN).

pdavis
+1  A: 

SQL Server's float is equivalent to .NET's System.Double.

This means that cast to float may lose precision due to rounding of the double value. Would be better to change type of _AccelLimit field to double.

Constantin
A: 

Ad normally you would never want to use float in SQL Server (or real) if you plan to perform math calculations on the data as it is an inexact datatype and it will introduce calculation errors. Use a decimal datatype instead if you need precision.

HLGEM
It is OK for most math and engineering calculations. Now, *financial and accounting* calculations are, of course, different.
Constantin
A: 

thanks! I also meet the same problem!

A: 

i kind have the same problem. i use the datasets, which convert the sql float values into c# double values. the problem is, that when i do an update of float values, they change in db: for example: the updated val_1 = 9.99 in c# goes as val_1 = 9.89999900012547 in database.

how do i avoid that, and update the exact values? the result i looking into is to have in database that 9.99 value.

If you think 9.99 is different from 9.9899999000... , you should not use floating point numbers. Google: "Goldberg floating point" for a simple but very good introduction to FP math. "Decimal" may be more appropriate for you.
MSalters
I suggest you start a new question and you will get better answers to your situation.
Keith Sirmons