How can I divide two integers to get a double?

C#MathIntDouble

C# Problem Overview


How do I divide two integers to get a double?

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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.

Solution 3 - C#

cast the integers to doubles.

Solution 4 - C#

Convert one of them to a double first. This form works in many languages:

 real_result = (int_numerator + 0.0) / int_denominator

Solution 5 - C#

var firstNumber=5000,
secondeNumber=37;

var decimalResult = decimal.Divide(firstNumber,secondeNumber);

Console.WriteLine(decimalResult );

Solution 6 - C#

var result = decimal.ToDouble(decimal.Divide(5, 2));

Solution 7 - C#

I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

Solution 8 - C#

The easiest way to do that is adding decimal places to your integer.

Ex.:

var v1 = 1 / 30 //the result is 0
var v2 = 1.00 / 30.00 //the result is 0.033333333333333333

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#NoahDView Answer on Stackoverflow
Solution 2 - C#fabriciorissettoView Answer on Stackoverflow
Solution 3 - C#Stephen WrightonView Answer on Stackoverflow
Solution 4 - C#Mark RansomView Answer on Stackoverflow
Solution 5 - C#Rejwanul RejaView Answer on Stackoverflow
Solution 6 - C#FrankView Answer on Stackoverflow
Solution 7 - C#MinhooDaView Answer on Stackoverflow
Solution 8 - C#FelipeHSouzaView Answer on Stackoverflow