Reputation: 626
I have an integer (representing seconds) which I'm converting to hours by dividing by 3600. I then store the value in a property (type int). If the value contains a decimal point, I convert it by casting. However, when I try to assign the value to the property, I get an error: "Cannot implicitly convert type 'decimal' to 'int'." Here's my code:
var p = ((Hours.Duration) / 3600.0);
(Hours.Duration) = p;
However,
Hours.Duration = (Hours.Duration) / 3600
works fine, and rounds to an int
. What am I doing wrong?
Upvotes: 0
Views: 2885
Reputation: 341
You can use this code:
int vIn = 0;
double vOut = Convert.ToDouble(vIn);
Here is a very handy convert data type webpage for those of others: Convert decimal to int in C#
Upvotes: 0
Reputation: 31
Don't define p as decimal. And the question is, if you want to include also partial hour (e.g. if the result for 4000/3600 would be 1 or 2). So you can write directly
Hours.Duration /= 3600;
or if you want count also partial hour
Hours.Duration = Hours.Duration / 3600 + ((Hours.Duration % 3600 > 0)?1:0);
or if you want correct rounding up
Hours.Duration = Hours.Duration / 3600 + ((Hours.Duration % 3600 >= 1800)?1:0);
Upvotes: 0
Reputation: 7116
decimal p = ((Hours.Duration) / 3600);
(Hours.Duration) = p;
you are getting error because p
is decimal and Hours.Duration is integer, You cannot assign decimal to int without explicit casting.
(Hours.Duration) = (int)p;
If Hours.Duration
is integer
, 3600 is also integer, then there will be an integer division, that is your decimal value will be lost. e.g. in integer division 7/2 =3
. If you want the answer to be 3.5, then you need to have atleast one decimal number in the division i.e 7.0/2 = 3.5
OR 7/2.0 = 3.5
.
Upvotes: 2