How to Convert float to int in Java

In this post we’ll see how to convert float to int in Java.

Considerations while converting float to int in Java

While converting float to int two things you need to consider are-

  1. Range of float is more than the int, if the float you are trying to convert to int is out of range for int then how to handle that.
  2. In float value there are fractional parts where as int doesn’t have fractional part so what to do with fractional part is another thing to consider. Fractional part can be truncated or you need to round it.

Converting using intValue() method or by type casting

You can convert float to int using intValue() method of the Float class (needs a Float object) or by explicitly type casting float value to int. In fact intValue() method implementation also do the type casting and returns the value of this Float as an int after a narrowing primitive conversion. Problem with these two methods is that the rounding to the nearest integer doesn’t happen while converting float to int, fractional part is truncated.

Converting float to int using intValue() method

Output

As you can see float value is truncated while converting it to int.

Converting float to int using explicit casting

Output

Converting float to int with rounding to nearest integer

The above two ways of converting float to int are not rounding the float to the nearest integer which is not what you’d want in most of the scenarios. In order to do that you should use Math.round(float a) method which returns the closest int to the passed argument.
Math.round() method also takes care of the special cases-

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Converting float to int using Math.round()

Output

If passed float value > Integer.MAX_VALUE

Output

This is the special case; since the passed float value is greater than or equal to the value of Integer.MAX_VALUE so Integer.MAX_VALUE is returned.

Example with different float arguments

Output

That’s all for the topic How to Convert float to int in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.