cast from decimal to int

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
 
J

Jon Skeet [C# MVP]

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"]
 
B

Bruce Wood

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top