Course contentsShow
← C
Lesson 864 of 1,21912. The Standard LibraryFree lesson

Rounding with `ceil`, `floor`, and `round`

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:

  1. floor(): This always looks down. It returns the largest integer less than or equal to your number. Even if you have 5.99, floor will drag it down to 5.0. It’s like a ball dropping to the basement floor.
  2. ceil(): Short for "ceiling," this always looks up. It returns the smallest integer greater than or equal to your number. Even if you have 5.01, ceil will push it up to 6.0.
  3. round(): This is the "fair" one we learned in school. If the decimal is .5 or higher, it goes up; otherwise, it goes down. 5.4 becomes 5.0, but 5.5 becomes 6.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 10giftcardsausercanbuywith10 gift cards a user can buy with 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.