I'm trying to cast the result of a divide result to an int in c#
This is my code:
decimal testDecimal = 5.00; // testDecimal always is dividable by 0.25 with 0 rest
int times=0;
int times = testDecimal / Convert.ToDecimal(0.250);
// error returned -> Cannot implicitly convert type 'decimal' to 'int'.
if I change my cast to
int times = (int) testDecimal / Convert.ToDecimal(0.250);
//also returns an error: Cannot implicitly convert type 'decimal' to 'int'
How could I get the result (20) as an integer? What am I doing wrong?
Try this:
times = (int)(testDecimal / Convert.ToDecimal(0.250));
Without the extra parenthesis, it is trying to convert ONLY testDecimal to integer, then trying to convert the int/decimal result to an integer implicitly, which is what causes the error.
In an unrelated note, you are trying to declare the variable 'times' twice.
As everybody answered, you have to add parenthesis to cast the result of the your division instead of just trying to cast the first part and then getting the error after the division.
I also want to point out that it is not necessary to use Convert.ToDecimal
just to declare your constant as adecimal, you could use C# suffixs to do so:
int times = (int)(testDecimal / 0.250m);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With