Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't do division

Tags:

c#

int h1 = 2;
int d1 = 4;
decimal c1 = d1/(d1+h1);
Console.WriteLine("{0:F9}", c1);

Console shows 0,00000000000, but I expected to see 0,6666666 and maybe 7 in the end. What's the problem? I tried different methods, but always see 0,00000000...

like image 546
John Smith Avatar asked Feb 21 '26 09:02

John Smith


1 Answers

It's because you're doing an integer division. You need to cast one value to decimal in order to do a decimal division :

int h1 = 2;
int d1 = 4;
decimal c1 = (decimal)d1 / (d1 + h1);

Basically, you can translate the current problematic behavior as:

decimal c1 = (decimal)(d1 / (d1 + h1));
decimal c1 = (decimal)(4 / (2 + 4));
decimal c1 = (decimal)(4 / 6);
decimal c1 = (decimal)(0); <-- Integer division
decimal c1 = 0m;

That's why you need either the numerator or denominator to be explicitly a decimal already.

Also, where you do the casting it is totally irrelevant, you just need to trigger the decimal division. Those 4 lines have exactly the same result :

decimal c1 = (decimal)d1 / (d1 + h1);
decimal c2 = d1 / ((decimal)d1 + h1);
decimal c3 = d1 / (d1 + (decimal)h1);
decimal c4 = d1 / (decimal)(d1 + h1);
like image 136
Pierre-Luc Pineault Avatar answered Feb 22 '26 22:02

Pierre-Luc Pineault