Explain Codes LogoExplain Codes Logo

How to convert float to int with Java

java
math-library
float-conversion
rounding-methods
Alex KataevbyAlex Kataev·Dec 30, 2024
TLDR

Convert a float to an int in Java using type casting, in which the decimal part is removed, leaving only the integer part.

// The "floor" is lava! 🔥 int myInt = (int) 9.99f; // Result: 9

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

// Doesn't discriminate against the .99! int roundedInt = Math.round(9.99f); // Result: 10

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.

float floatValue = 9.99f; // Only cares about whole numbers. Decimals are overrated anyway! int castedInt = (int) floatValue; // Result: 9 // Float's best friend! Gets you closer to the actual value. int roundedInt = Math.round(floatValue); // Result: 10

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.

// I'm positive this isn't how you handle negatives! int negativeInt = (int) -9.99f; // Result: -9

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():

// No decimals will be harmed in this conversion! int towardsZero = (floatValue > 0) ? (int) Math.floor(floatValue) : (int) Math.ceil(floatValue);

Rounding to even numbers

If specific rounding towards the nearest even number is needed, Java provides the Math.rint() function:

// Even Steven's favorite! int evenInt = (int) Math.rint(9.5f); // Result: 10

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:

// I love it when you call me an Integer! Float floatObject = new Float(9.99f); int intValue = floatObject.intValue(); // Result: 9

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:

// Always look on the bright side of converting! int roundedPositive = (int)(floatValue + 0.5f);

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:

// When a Float wants to dress up as an Integer for Halloween 🎃! int number = Float.valueOf(floatValue).intValue();

Custom rounding with BigDecimal

When high precision and customizable rounding modes are a requirement, BigDecimal provides a powerful alternative:

// Because floating point precision matters! int preciseInt = new BigDecimal(floatValue).setScale(0, RoundingMode.HALF_UP).intValue();