Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# is rounding down divisions by itself

Tags:

c#

division

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?

like image 761
ONOZ Avatar asked Jun 10 '11 20:06

ONOZ


2 Answers

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.

like image 62
rsbarro Avatar answered Oct 15 '22 02:10

rsbarro


200/3 is integer division, resulting in an integer.

try 200.0/3.0

like image 27
John Boker Avatar answered Oct 15 '22 01:10

John Boker