how would you go about converting a float to an int?
That depends on what you want to have happen to the fractional part.
If you want to chop it off, you can cast:
float floatValue = 2.7f;
int value = (int)floatValue;
System.out.println(value); // 2
If you want to round it, use the various rounding methods in the JDK's library, such as Math.round(float)
.
float floatValue = 2.7f;
int value = Math.round(floatValue);
System.out.println(value); // 3
Re your comment:
I am looking more for a way to find the reciprocal of the value, not the rounded value. For example, if I had 0.25 as my value, then I would like to receive 4 for my output, etc.
If the reciprocal is one over the value, then:
float input = 0.25f;
int recip = (int)(1.0f / input);
System.out.println(recip); // 4
...which chops off any fractional part, or
float input = 0.25f;
int recip = Math.round(1.0f / input);
System.out.println(recip); // 4
...which rounds it. (And there are other rounding methods that give you control over half-up vs. half-down vs. half-even, vs. rounding toward zero rather than positive infinity, etc.)
Side note: There's almost never a good reason to use float
as opposed to double
. And note that decimal constants, e.g. 2.0
, are double
s. If you want float
s, put an f
at the end: 2.0f
. But again: Use double
. :-)