views:

109

answers:

3
int num = 5;
int denom = 7;
double d = num / denom;

this results in 0, I know you can force it to work by doing

double d = ((double) num) / denom;

but there has to be another way, right? I don't like casting primitives, who knows what may happen.

+7  A: 
double num = 5;

That avoids a cast. But you'll find that the cast conversions are well-defined. You don't have to guess, just check the JLS. int to double is a widening conversion. From §5.1.2:

Widening primitive conversions do not lose information about the overall magnitude of a numeric value.

[...]

Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode (§4.2.4).

5 can be expressed exactly as a double.

Matthew Flaschen
+1. Stop being scared of casting. Learn how it works. It's all well-defined.
Mark Peters
+7  A: 

What's wrong with casting primitives?

If you don't want to cast for some reason, you could do

double d = num * 1.0 / denom;
Paul Tomblin
A: 

I don't like casting primitives, who knows what may happen.

Why do you have an irrational fear of casting primitives? Nothing bad will happen when you cast an int to a double. If you're just not sure of how it works, look it up in the Java Language Specification. Casting an int to double is a widening primitive conversion.

You can get rid of the extra pair of parentheses by casting the denominator instead of the numerator:

double d = num / (double) denom;
Jesper
you can as well do `double d = (double) num / denom;`... (OK, this one depends on precedence)
Carlos Heuberger