Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I divide two integers to get a double?

Tags:

c#

int

math

double

How do I divide two integers to get a double?

like image 305
leora Avatar asked Mar 19 '09 04:03

leora


People also ask

How do you double a value after division in C++?

If you want to keep a and b as int s, yet divide them fully, you must cast at least one of them to double: (double)a/b or a/(double)b or (double)a/(double)b . b) c is a double , so it can accept an int value on assignement: the int is automatically converted to double and assigned to c .

What happens when you divide two integers?

Recall that the fraction bar can be read “divided by.” Therefore, 8/2 can be read as “8 divided by 2.” Rule for Dividing Two Integers: TO DIVIDE TWO NUMBERS WITH THE SAME SIGN, divide the absolute values of the numbers. The quotient is positive.

How do you divide multiple integers?

Division of integers involves the grouping of items. It includes both positive numbers and negative numbers. Just like multiplication, the division of integers also involves the same cases. When you divide integers with two positive signs, Positive ÷ Positive = Positive → 16 ÷ 8 = 2.


2 Answers

You want to cast the numbers:

double num3 = (double)num1/(double)num2; 

Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:

double num3 = (double)num1/num2; 

For more information see:

Dot Net Perls

like image 74
NoahD Avatar answered Oct 20 '22 10:10

NoahD


Complementing the @NoahD's answer

To have a greater precision you can cast to decimal:

(decimal)100/863 //0.1158748551564310544611819235 

Or:

Decimal.Divide(100, 863) //0.1158748551564310544611819235 

Double are represented allocating 64 bits while decimal uses 128

(double)100/863 //0.11587485515643106 

In depth explanation of "precision"

For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats and doubles and this one where he talks about decimals.

like image 35
fabriciorissetto Avatar answered Oct 20 '22 08:10

fabriciorissetto