How can I convert integer into float in Java?

Roman picture Roman · Dec 7, 2010 · Viewed 315.5k times · Source

I have two integers x and y. I need to calculate x/y and as outcome I would like to get float. For example as an outcome of 3/2 I would like to have 1.5. I thought that easiest (or the only) way to do it is to convert x and y into float type. Unfortunately, I cannot find an easy way to do it. Could you please help me with that?

Answer

Matt Ball picture Matt Ball · Dec 7, 2010

You just need to cast at least one of the operands to a float:

float z = (float) x / y;

or

float z = x / (float) y;

or (unnecessary)

float z = (float) x / (float) y;