0

My C# ExecuteScalar command was throwing an invalid cast from my call when assigning to a float even though the return value from the SQL was a float. So I did a simple test as follows:

            sqlCU = "select cast(1 as float)";
            using (SqlCommand command = new SqlCommand(sqlCU, con))
            {
                object cuP5300x = command.ExecuteScalar();
            }

What comes back is always a double.

So to fix it I have to do something what I think is rather silly:

float cuP5300x = (float)((double)command.ExecuteScalar())

because as mentioned

float cuP5300x = (float)command.ExecuteScalar();

Causes an invalid cast exception.

Can anyone explain why, I cannot find anything in the MS Documentation to say that floats are doubles, and is there a more sensible way...?

thanks.

Neil Walker
  • 6,400
  • 14
  • 57
  • 86
  • Possible duplicate of [Why is a SQL float different from a C# float](https://stackoverflow.com/questions/122523/why-is-a-sql-float-different-from-a-c-sharp-float) – mjwills Nov 28 '18 at 12:27
  • What happens if you use `real` rather than `float`? – mjwills Nov 28 '18 at 12:28
  • Or you can simply use `Convert.ToFloat(command.ExecuteScalar())` and stop worrying about the returned value type. But you still need to consider DbNull, though – Andrey Nikolov Nov 28 '18 at 12:31
  • Thanks, Convert looks nicer than my double cast, but btw, it's ToSingle not ToFloat :) – Neil Walker Nov 28 '18 at 12:34

1 Answers1

2

"Can anyone explain why, I cannot find anything in the MS Documentation to say that floats are doubles, and is there a more sensible way...?"

It is in the documentation: SQL Server Data Type Mappings.

Specifically this states , for the SQL Server Database Engine type Float the .NET Framework Type is Double. Also the SqlDbType enumeration is Float, the SqlDataReader SqlTypes typed accessor is GetSqlDouble, the DbType enumeration is Double and the SqlDataReader DbType typed accessor is GetDouble.

SQL Server Database Engine type NET Framework type SqlDbType enumeration SqlDataReader SqlTypes typed accessor DbType enumeration SqlDataReader DbType typed accessor
------------------------------- ------------------ --------------------- ------------------------------------- ------------------ -----------------------------------
float                           Double             Float                 GetSqlDouble                          Double             GetDouble
Thom A
  • 88,727
  • 11
  • 45
  • 75
  • Ah, thanks, I never found THAT page. Looking at it it never crossed my mind to think that 'double' does not exist in SQL Server so might be float and not just another 'number(x,x)' – Neil Walker Nov 28 '18 at 12:28