leora
leora

Reputation: 196791

How can I divide two integers to get a double?

How do I divide two integers to get a double?

Upvotes: 381

Views: 360831

Answers (9)

Bidder
Bidder

Reputation: 320

In the comment to the accepted answer there is a distinction made which seems to be worth highlighting in a separate answer.

The correct code:

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

is not the same as casting the result of integer division:

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

Given num1 = 7 and num2 = 12:

The correct code will result in num3 = 0.5833333

Casting the result of integer division will result in num3 = 0.00

Upvotes: 2

FelipeHSouza
FelipeHSouza

Reputation: 375

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

Upvotes: 1

MinhooDa
MinhooDa

Reputation: 1

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.

Upvotes: 0

Frank
Frank

Reputation: 71

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

Upvotes: 5

fabriciorissetto
fabriciorissetto

Reputation: 10083

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.

Upvotes: 51

Rejwanul Reja
Rejwanul Reja

Reputation: 1491

var firstNumber=5000,
secondeNumber=37;

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

Console.WriteLine(decimalResult );

Upvotes: 4

NoahD
NoahD

Reputation: 8302

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

Upvotes: 585

Stephen Wrighton
Stephen Wrighton

Reputation: 37850

cast the integers to doubles.

Upvotes: 10

Mark Ransom
Mark Ransom

Reputation: 308520

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

 real_result = (int_numerator + 0.0) / int_denominator

Upvotes: 9

Related Questions