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? 
5
  • 5
    FYI: Don't be surprised if the results seem wrong. Commented Mar 5, 2011 at 10:07
  • You might also want to check this SO post 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. Commented Mar 5, 2011 at 10:19
  • I suggest you use double instead of float as float cannot represent all int values accurately. try (double) integer1 / integer2 Commented Mar 5, 2011 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. :) Commented Mar 7, 2011 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) Commented Mar 7, 2011 at 12:23

1 Answer 1

25

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

float result = integer1 / (float) integer2 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.