1/252 = 0 in c#?

Yes – that calculation is being performed in integer arithmetic. Try this:

double num = 1.0 / 252.0;

Basically, the type of the variable that the result is being assigned to doesn’t affect the arithmetic operation being performed. The result of dividing one integer by another is an integer; if you want floating point arithmetic to be used, you need to make one or other of the operands a floating point type. One simple way of doing that with literals is to stick “.0” on the end. Another alternative is to use the d suffix:

double num = 1d / 252d;

Note that you only really need to make one operand a floating point value for it to work, but for clarity I’d probably do both in this case.

That’s easy to do with literals of course, but for other expressions (variables, the results of method calls etc) you’d need to use a cast:

int x = 1;
int y = 252;
double num = (double) x / (double) y;

Again, you only need to cast one of them, so this would work too:

int x = 1;
int y = 252;
double num = (double) x / y;

Note that this isn’t specific to division – it affects the other arithmetic operators too.

Leave a Comment