Official C Library Rounding Functions

Nestled within the C Library are various functions mathematical, a handful of which are used to round floating point values. The most common of them are ceil(), floor(), and rint().

These three functions parallel those I asked you to create for this month’s Exercise, so I hope that you’ve already completed the exercise and are not reading this Lesson to cheat.

All the rounding functions listed are declared in the math.h header file. Here’s how each works:

ceil() takes an floating point value, rounds it up to the next whole number (integer), and returns that value (as a floating point). This function’s name most likely comes from the word “ceiling.” Say “see ill” and you won’t forget how to spell it.

floor() takes a floating point value, rounds it down to the next whole number, and returns that value.

rint() is the “round integer” function. It takes a floating point value and rounds it up or down to the next integer. The man page claims that the function uses “the prevailing rounding mode” to determine whether to round up or down. I’ve no idea how that works.

The following code is a modification of this month’s Exercise solution. It uses ceil(), floor(), and rint() to replace the roundup(), rounddown(), and roundhalf() functions required for that exercise:

#include <stdio.h>
#include <math.h>

int main()
{
    float v1,v2;

    v1 = 1234.56789;
    v2 = 98765.4321;

    printf("Value v1 = %f\n",v1);
    printf("Value v2 = %f\n",v2);
    printf("Rounded up:\t%f\t%f\n",
            ceil(v1),
            ceil(v2));
    printf("Rounded down:\t%f\t%f\n",
            floor(v1),
            floor(v2));
    printf("Rounded half:\t%f\t%f\n",
            rint(v1),
            rint(v2));

    return(0);
}

The output from this code is identical to the solution for this month’s Exercise:

Value v1 = 1234.567871
Value v2 = 98765.429688
Rounded up:	1235.000000	98766.000000
Rounded down:	1234.000000	98765.000000
Rounded half:	1235.000000	98765.000000