Truncation during float-to-int casts
What you'll learn: How C handles the conversion from decimal numbers to whole numbers by discarding everything after the decimal point.
The "Chop" Rule
When you force a floating-point number (like a float or double) into an integer variable, C has a very specific way of handling the extra data. It doesn't round to the nearest neighbor, and it doesn't look at whether the fraction is large or small. Instead, it performs truncation.
Think of truncation like a physical barrier. Imagine you are trying to push a long wooden plank through a doorway that is too short. Rather than trying to fold the plank or find a creative way to fit it, C simply takes a saw and cuts off everything that doesn't fit. The part that falls onto the floor is gone forever.
How it works in code
In C, you perform an explicit cast by placing the desired type in parentheses, like (int)myFloat. When you do this, the compiler ignores the decimal portion entirely. It doesn't matter if your number is 4.1 or 4.9999; the result will be 4.
#include <stdio.h>
int main() {
float pi = 3.14159f;
float almostFive = 4.999f;
// Explicitly casting floats to ints
int truncatedPi = (int)pi;
int truncatedFive = (int)almostFive;
printf("Pi became: %d\n", truncatedPi); // Output: 3
printf("Almost five became: %d\n", truncatedFive); // Output: 4
return 0;
}
Loss of Precision
It is important to remember that this process is "lossy." Once you cast 4.999 to an int, the .999 is deleted from memory. You cannot "un-cast" it later to get those decimals back.
This behavior is particularly tricky with negative numbers. If you cast -2.8 to an int, the result is -2. C always truncates toward zero. It doesn't move toward the "lower" number on the number line; it simply deletes the fractional tail. This makes explicit casting a powerful tool for isolating the whole-number part of a value, but a dangerous one if you were expecting standard mathematical rounding.
Key takeaway
Casting a float to an int always truncates the decimal, effectively "chopping off" the fraction without rounding.