C# is rounding down divisions by itself

ONOZ picture ONOZ · Jun 10, 2011 · Viewed 32.2k times · Source

When I make a division in C#, it automaticaly rounds down. See this example:

double i;
i = 200 / 3;
Messagebox.Show(i.ToString());

This shows me a messagebox containing "66". 200 / 3 is actually 66.66666~ however.

Is there a way I can avoid this rounding down and keep a number like 66.6666667?

Answer

rsbarro picture rsbarro · Jun 10, 2011

i = 200 / 3 is performing integer division.

Try either:

i = (double)200 / 3

or

i = 200.0 / 3

or

i = 200d / 3

Declaring one of the constants as a double will cause the double division operator to be used.