Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide two decimals and cast result to int

Tags:

c#

casting

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?

like image 377
user3127554 Avatar asked Mar 05 '23 21:03

user3127554


2 Answers

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.

like image 57
Andrew Drake Avatar answered Mar 17 '23 21:03

Andrew Drake


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);
like image 36
Haytam Avatar answered Mar 17 '23 20:03

Haytam