Course contentsShow
← Java
Lesson 81 of 2,8702. Variables and Primitive TypesFree lesson

Precision Loss in Floating-Point to Integer Casts

Learn how casting double or float to int discards the fractional part and can overflow integer limits.

Precision Loss in Floating-Point to Integer Casts

You'll learn how casting floating-point numbers to integers discards fractional parts and can exceed integer limits.

When you cast a double or float to an int, long, short, or byte, Java performs a narrowing conversion that fundamentally changes how the number is represented. Unlike integer-to-integer narrowing (which wraps around), floating-point-to-integer casts have two important behaviors:

The Fractional Part Vanishes

The decimal portion is simply discarded, not rounded. Think of it like sawing off the fractional part of a ruler—3.9 inches becomes 3 inches, not 4.

double price = 19.99;
int dollars = (int) price;  // dollars = 19, not 20

The .99 disappears completely. This is called truncation toward zero: positive numbers round down, negative numbers round up (toward zero).

double temp = -5.8;
int rounded = (int) temp;  // rounded = -5, not -6

Integer Overflow Danger

If the floating-point value exceeds the integer type's range, the result is unpredictable—often wrapping to the minimum or maximum value of that type. A double holding 1.5e10 (15 billion) cast to int won't fit, since int maxes out around 2.1 billion.

double huge = 3.5e9;
int compressed = (int) huge;  // Result: 2147483647 (Integer.MAX_VALUE)

Always ensure your floating-point value fits within the target integer type's range before casting.

Key Takeaway: Casting float or double to an integer type truncates the fractional part (never rounds) and can overflow integer limits, potentially producing unexpected values.