cast from decimal to int

  • Thread starter Thread starter Dan Holmes
  • Start date Start date
D

Dan Holmes

i have a datareader that pulls a field of type numeric(18, 0). the
debugger shows the field as {decimal}. I want to cast it to an int.
This doesn't work (int)dr["field1"]:. Is that because the definition of
the column would overflow an int? So i would have to do something like
int.Parse(dr["field1"].ToString());

dan
 
Dan Holmes said:
i have a datareader that pulls a field of type numeric(18, 0). the
debugger shows the field as {decimal}. I want to cast it to an int.
This doesn't work (int)dr["field1"]:. Is that because the definition of
the column would overflow an int? So i would have to do something like
int.Parse(dr["field1"].ToString());

It's because the DataRow indexer is declared to return Object. The cast
is therefore treated as an unboxing conversion, which has to be of the
exactly correct type. What you want is to unbox to decimal and then
cast to int:

(int)(decimal)dr["field1"]
 
Dan said:
i have a datareader that pulls a field of type numeric(18, 0). the
debugger shows the field as {decimal}. I want to cast it to an int.
This doesn't work (int)dr["field1"]:. Is that because the definition of
the column would overflow an int? So i would have to do something like
int.Parse(dr["field1"].ToString());

I believe that you have to cast in two steps... that you can't unbox
the value and cast it all in one go. If you say

decimal f1 = (decimal)dr["field1"];

then this will unbox the value, then you can say:

int i1 = (int)f1;

to do the cast. You might even be able to do this:

int i1 = (int)((decimal)dr["field1"]);

but I'm not 100% sure without trying it myself.
 
Back
Top