8

I need to perform division between integers in Java, and the result should be a float.

Could I just use / symbol for it? As in:

int integer1 = 1;
int integer2 = 2;
float quotient = integer1 / integer2; // Could I do this?
Makoto
  • 104,088
  • 27
  • 192
  • 230
aneuryzm
  • 63,052
  • 100
  • 273
  • 488
  • 5
    FYI: [Don't be surprised if the results seem wrong.](http://floating-point-gui.de/) – Adam Paynter Mar 05 '11 at 10:07
  • You might also want to check [this SO post](http://stackoverflow.com/questions/474535/best-way-to-represent-a-fraction-in-java) dealing with fractions. If you're going to use your division result in other calculations, you'll need all help you can get to minimize rounding errors. – darioo Mar 05 '11 at 10:19
  • I suggest you use `double` instead of `float` as `float` cannot represent all `int` values accurately. try `(double) integer1 / integer2` – Peter Lawrey Mar 05 '11 at 15:17
  • @Peter: I agree. For the record, `double` is merely less bad than `float`. It doesn't solve the problem. I presume you already knew that, but I just wanted it to be on the record. :) – Adam Paynter Mar 07 '11 at 12:13
  • 2
    @Adam, 'double' can at least repesent all `int` values without error. It cannot represent all `int`/`int` values without error, but there is likely to be approriate rounding which is acceptible for the OPs applications. Otherwise you need to use a Faction (for unlimited precision) or BigDecimal (for very long precision) – Peter Lawrey Mar 07 '11 at 12:23

1 Answers1

25

Cast one of the integers to float to ensure a floating point division:

float result = integer1 / (float) integer2
Adrian Cox
  • 6,204
  • 5
  • 41
  • 68