How to convert float to int with Java
Convert a float to an int in Java using type casting, in which the decimal part is removed, leaving only the integer part.
Remember, there's no rounding here - only a "decimal-ectomy".
However, this approach could lead to precision loss in round-to-nearest conversions. Let's examine more precise alternatives.
Forge the path: Math.round()
For superior precision while converting a float to an int, Java's Math library comes to the rescue with Math.round(floatValue)
:
Unlike mere casting, Math.round()
rounds off to the nearest integer.
Direct casting vs rounding
Java's native type casting truncates the decimal part of the float, which might lead to less accurate results compared to the Math.round()
method.
Master the quirks: Negative numbers
Negative float values need special care while converting to integer. A direct cast truncates the negative float value, which behaves counter-intuitively.
In contrast, Math.round(-9.99f)
would yield -10
, as it heads towards the nearest integer.
Customize your rounding
When integer conversion isn't as simple as rounding to nearest, Java provides additional methods:
Leaning towards zero
Sometimes your application might need to round the float towards zero. This can be achieved by judiciously using Math.floor()
or Math.ceil()
:
Rounding to even numbers
If specific rounding towards the nearest even number is needed, Java provides the Math.rint()
function:
Converting via a Float object
For folks who appreciate an object-oriented approach, Java also allows us to convert floating point values to integer using a Float
object:
Edge cases: Infinity and beyond
In computations involving large numbers, special float values such as Float.POSITIVE_INFINITY
, Float.NEGATIVE_INFINITY
, and Float.NaN
might appear. These need to be handled judiciously while converting to an integer.
Targeted rounding
In certain use cases, you may even want to nudge your float towards rounding by adding 0.5
to it before casting:
This method works best with positive numbers.
Converting boxed float to Integer
The Float
class provides additional methods for conversions, which come in handy when operating with boxed floats:
Custom rounding with BigDecimal
When high precision and customizable rounding modes are a requirement, BigDecimal
provides a powerful alternative:
Was this article helpful?