0

I'm retrieving some data with a SqlDataReader and trying to convert one of these objects to a float (the same as its data type in the database).

What I have:

u.unitid = (float)Convert.ToSingle((reader["UNITID"]));

This returns a "0" for every unitid.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sartorialist
  • 291
  • 2
  • 18
  • have you tried converting it directly to float instead of first converting it tosingle then casting it to float? – Anjo Apr 18 '18 at 14:57
  • 1
    It makes no sense to case the result of `ToSingle` to `float` since it is already a `float`. Have you tried the `reader.GetFloat()` method? What is the column type of `UNITED` in the database? – Chris Dunaway Apr 18 '18 at 14:59
  • 2
    ToSingle already gives a float, why second cast? Also, what are the values of unitid? – Andrei Apr 18 '18 at 14:59
  • Did you know DataReaders have a number of typed `Getxxxx` methods such as `GetSingle()`? If it always returns 0 for any row consider that the query may be wrong etc – Ňɏssa Pøngjǣrdenlarp Apr 18 '18 at 15:05
  • `Single` is the CLR name that C# aliases as `float`. They are the same, the cast is not necessary. – JamesFaix Apr 18 '18 at 15:05
  • Can you run this in a step-thru debugger with `object o = reader["UNITID"];` on one line and `u.unitid = Convert.ToSingle(o);` on the next line. That way you can see what the returned value actually is before converting. – JamesFaix Apr 18 '18 at 15:06
  • The values of UNITID are 6-8 digit integers. It's datatype in database and in model is float. – Sartorialist Apr 18 '18 at 15:23
  • did you try float.Parse(reader["UNITID"].ToString());? – user9405863 Apr 18 '18 at 15:54
  • [The SQL type `FLOAT` corresponds to the .NET `Double` data type](https://stackoverflow.com/a/37344567/4137916), and should be read using `.GetDouble()`. That said, `Convert` should still work if `UNITID` really holds non-zero doubles. – Jeroen Mostert Apr 18 '18 at 16:43
  • @JeroenMostert Thank you! GetDouble worked. – Sartorialist Apr 18 '18 at 16:59

0 Answers0