Why I cannot the get percentage by using Int

Daoming Yang picture Daoming Yang · Apr 8, 2010 · Viewed 16.9k times · Source

Please forgive my programming knowledge. I know this is a simple thing, but I do not understand why result is always 0. Why decimal will be fine?

int a = 100;
int b = 200;
decimal c = (a / b) * 100;

Many thanks.

Answer

Adam Robinson picture Adam Robinson · Apr 8, 2010

Integer division always truncates the remainder. This is done at the time that the number is divided, not when it's assigned to the variable (as I'm guessing you assumed).

decimal c = ((decimal)a / b) * 100;