user2352923 - 27 days ago 5
Java Question

# Get a float's reciprocal?

I know getting the reciprocal of an int would go something like this:

``````int foo = 5;
float recip = 1/foo;
``````

but how would you go about getting the reciprocal of a float? Would it go the same way? Right now I have the user inputting the reciprocal, which is not optimal. Any ideas?

EDIT

For clarification here's some pseudo-code:

``````float input = 0.25;
int recip = (get reciprocal here);
System.out.println(recip); //should return 4
``````

Thanks!

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
``````

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`. :-)

Source (Stackoverflow)