Rounding with ceil, floor, and round
What you'll learn: How to use the C standard library to control how decimal numbers are converted into whole numbers.
In programming, we often need to strip away the decimals from a double or float. While simply casting a number to an int always chops off the decimal (truncation), the math.h library gives you three precise tools to decide exactly how that rounding happens.
The Three Directions
Think of these functions as different sets of instructions for a traveler on a vertical ladder:
floor(): This always looks down. It returns the largest integer less than or equal to your number. Even if you have5.99,floorwill drag it down to5.0. It’s like a ball dropping to the basement floor.ceil(): Short for "ceiling," this always looks up. It returns the smallest integer greater than or equal to your number. Even if you have5.01,ceilwill push it up to6.0.round(): This is the "fair" one we learned in school. If the decimal is.5or higher, it goes up; otherwise, it goes down.5.4becomes5.0, but5.5becomes6.0.
Coding the Rounding
To use these, you must include <math.h> at the top of your file. Note that these functions return a double, not an int, so they keep their decimal point (e.g., 5.0).
#include <stdio.h>
#include <math.h>
int main() {
double myNum = 5.25;
printf("Original: %.2f\n", myNum);
// Always rounds UP
printf("Ceil: %.1f\n", ceil(myNum)); // Result: 6.0
// Always rounds DOWN
printf("Floor: %.1f\n", floor(myNum)); // Result: 5.0
// Rounds to the NEAREST
printf("Round: %.1f\n", round(myNum)); // Result: 5.0
return 0;
}
Why use them?
Imagine you are building a shopping cart. If a user buys 2.1 containers of flour, you can't ship a partial container, so you use ceil() to charge them for 3. Conversely, if you are calculating how many full 25.99, you use floor() because they don't quite have enough for that third card.
Key takeaway
Use ceil() to round up, floor() to round down, and round() for standard mathematical rounding.