🌐
W3Schools
w3schools.com › c › ref_math_ceil.php
C Math ceil() Function
The ceil() function is defined in the <math.h> header file. Tip: To round a number DOWN to the nearest integer, look at the floor() function. Tip: To round a number to the nearest integer in either direction, look at the round() function. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com
🌐
Programiz
programiz.com › c-programming › library-function › math.h › ceil
C ceil() - C Standard Library
The ceil() function computes the nearest integer greater than the argument passed.
People also ask

What is the ceil() function in C?
The ceil() function in C is a math function used to round any floating-point number up to the nearest integer. It is available in the math.h library and returns a double value.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › ceil function in c
Ceil() Function in C: Syntax, Usage & Examples
What is the ceil value?
The ceil() function calculates the next highest whole number greater than or equal to x.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › ceil function in c
Ceil() Function in C: Syntax, Usage & Examples
What are the alternatives to ceil() function in C?
Alternatives include floor() for rounding down and round() for the nearest integer. You can also use manual logic, but using built-in functions like ceil() is safer and more readable in C.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › ceil function in c
Ceil() Function in C: Syntax, Usage & Examples
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_ceil.htm
C library - ceil() function
The C library ceil() function of type double accept the single argument(x) that returns the smallest integer value greater than or equal to, by the given value. This method rounded up the nearest integer.
🌐
Cppreference
en.cppreference.com › w › c › numeric › math › ceil
ceil, ceilf, ceill - cppreference.com
May 23, 2024 - #include <math.h> #include <stdio.h> int main(void) { printf("ceil(+2.4) = %+.1f\n", ceil(2.4)); printf("ceil(-2.4) = %+.1f\n", ceil(-2.4)); printf("ceil(-0.0) = %+.1f\n", ceil(-0.0)); printf("ceil(-Inf) = %+f\n", ceil(-INFINITY)); }
🌐
GeeksforGeeks
geeksforgeeks.org › c language › c-ceil-function
C ceil() Function - GeeksforGeeks
July 7, 2024 - It is defined inside the <math.h> ... double, or long double. The ceil() function returns the smallest integer value greater than or equal to the input number as a double....
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › ceil function in c
Ceil() Function in C: Syntax, Usage & Examples
April 23, 2025 - ... Parameter: A floating-point number (x) to round up.Return value: The smallest integer value greater than or equal to x, returned as a double. The ceil() function accepts a single argument and returns an integer value.
🌐
O'Reilly
oreilly.com › library › view › c-in-a › 0596006977 › re31.html
ceil - C in a Nutshell [Book]
December 16, 2005 - The ceil() function returns the smallest integer that is greater than or equal to its argument. However, the function does not have an integer type; it returns an integer value, but with a floating-point type.
Authors   Peter PrinzTony Crawford
Published   2005
Pages   618
🌐
TechOnTheNet
techonthenet.com › c_language › standard_library_functions › math_h › ceil.php
C Language: ceil function (Ceiling)
/* Example using ceil by TechOnTheNet.com */ #include <stdio.h> #include <math.h> int main(int argc, const char * argv[]) { /* Define temporary variables */ double value; double result; /* Assign the value we will find the ceil of */ value = 1.6; /* Calculate the ceil of value */ result = ceil(value); /* Display the result of the calculation */ printf("The ceil of %f is %f\n", value, result); return 0; }
Find elsewhere
🌐
W3Resource
w3resource.com › c-programming › math › c-ceil.php
C ceil() function
December 24, 2022 - #include <math.h> #include <stdio.h> int main(void) { double x, y, z; x = 123.345; y = 1.05; z = -1.05; printf("Before applying ceil():"); printf("\nx = %.3f ; y = %.2f ; z = %.2f\n", x, y, z); x = ceil(123.345); y = ceil(1.05); z = ceil(-1.05); printf("\n\nAfter applying ceil():"); printf("\nx = %.3f ; y = %.2f ; z = %.2f\n", x, y, z); } ... Before applying ceil(): x = 123.345 ; y = 1.05 ; z = -1.05 After applying ceil(): x = 124.000 ; y = 2.00 ; z = -1.00
🌐
W3Schools
w3schools.com › c › ref_math_floor.php
C Math floor() Function
Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number to the nearest integer in either direction, look at the round() function. ... If you want to use W3Schools services as an educational institution, ...
🌐
Programiz
programiz.com › cpp-programming › library-function › cmath › ceil
C++ ceil() - C++ Standard Library
double ceil(double num); float ceil(float num); long double ceil(long double num); // for integral types double ceil(T num); #include <iostream> #include <cmath> using namespace std; int main() { double num = 10.25;
🌐
Google Translate
translate.google.com › translate
Función ceil() de C Math
ceil(double number); ❮ Math Functions · C Functions Tutorial · C Math Functions Tutorial · ★ +1 · Sign in to track progress · REMOVE ADS · PLUS · SPACES · GET CERTIFIED · FOR TEACHERS · BOOTCAMPS · CONTACT US · × · If you want ...
🌐
Fresh2Refresh
fresh2refresh.com › home › c programming tutorial › c – arithmetic functions › c – ceil() function
C ceil() function | C Arithmetic functions | Fresh2Refresh
September 23, 2020 - C ceil() function:ceil( ) function in C returns nearest integer value which is greater than or equal to the argument passed to this function.
🌐
Programming Simplified
programmingsimplified.com › c › math.h › ceil
ceil in C - math.h | Programming Simplified
Ceil function is used to round up a number i.e. it returns the smallest number which is greater than argument passed to it · Declaration: double ceil(double);
🌐
Quora
quora.com › What-is-the-use-of-ceil-in-C-with-examples
What is the use of ceil in C, with examples? - Quora
Answer (1 of 5): C Language: ceil function (Ceiling) In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
Top answer
1 of 4
3

The macro you quoted definitely won't work correctly for numbers that are greater than INT_MAX but which can still be represented exactly as a double.

The only way to implement ceil() correctly (assuming you can't implement it using an equivalent assembly instruction) is to do bit-twiddling on the binary representation of the floating point number, as is done in the s_ceil.c source file behind your first link. Understanding how the code works requires an understanding of the floating point representation of the underlying platform -- the representation is most probably going to be IEEE 754 -- but there's no way around this.

Edit:

Some of the complexities in s_ceil.c stem from the special cases it handles (NaNs, infinities) and the fact that it needs to do its work without being able to assume that a 64-bit integral type exists.

The basic idea of all the bit-twiddling is to mask off the fractional bits of the mantissa and add 1 to it if the number is greater than zero... but there's a bit of additional logic involved as well to make sure you do the right thing in all cases.

Here's a illustrative version of ceil() for floats that I cobbled together. Beware: This does not handle the special cases correctly and it is not tested extensively -- so don't actually use it. It does however serve to illustrate the principles involved in the bit-twiddling. I've tried to comment the routine extensively, but the comments do assume that you understand how floating point numbers are represented in IEEE 754 format.

union float_int
{
    float f;
    int i;
};

float myceil(float x)
{
    float_int val;
    val.f=x;

    // Extract sign, exponent and mantissa
    // Bias is removed from exponent
    int sign=val.i >> 31;
    int exponent=((val.i & 0x7fffffff) >> 23) - 127;
    int mantissa=val.i & 0x7fffff;

    // Is the exponent less than zero?
    if(exponent<0) 
    {   
        // In this case, x is in the open interval (-1, 1)
        if(x<=0.0f)
            return 0.0f;
        else
            return 1.0f;
    }
    else
    {
        // Construct a bit mask that will mask off the
        // fractional part of the mantissa
        int mask=0x7fffff >> exponent;

        // Is x already an integer (i.e. are all the
        // fractional bits zero?)
        if((mantissa & mask) == 0)
            return x;
        else
        {
            // If x is positive, we need to add 1 to it
            // before clearing the fractional bits
            if(!sign)
            {
                mantissa+=1 << (23-exponent);

                // Did the mantissa overflow?
                if(mantissa & 0x800000)
                {
                    // The mantissa can only overflow if all the
                    // integer bits were previously 1 -- so we can
                    // just clear out the mantissa and increment
                    // the exponent
                    mantissa=0;
                    exponent++;
                }
            }

            // Clear the fractional bits
            mantissa&=~mask;
        }
    }

    // Put sign, exponent and mantissa together again
    val.i=(sign << 31) | ((exponent+127) << 23) | mantissa;

    return val.f;
}
2 of 4
3

Nothing you will write is more elegant than using the standard library implementation. No code at all is always more elegant than elegant code.

That aside, this approach has two major flaws:

  • If X is greater than INT_MAX + 1 or less than INT_MIN - 1, the behavior of your macro is undefined. This means that your implementation may give incorrect results for nearly half of all floating-point numbers. You will also raise the invalid flag, contrary to IEEE-754.
  • It gets the edge cases for -0, +/-infinity, and nan wrong. In fact, the only edge case it gets right is +0.

You can implement ceil in manner similar to what you tried, like so (this implementation assumes IEEE-754 double precision):

#include <math.h>

double ceil(double x) {
    // All floating-point numbers larger than 2^52 are exact integers, so we
    // simply return x for those inputs.  We also handle ceil(nan) = nan here.
    if (isnan(x) || fabs(x) >= 0x1.0p52) return x;
    // Now we know that |x| < 2^52, and therefore we can use conversion to
    // long long to force truncation of x without risking undefined behavior.
    const double truncation = (long long)x;
    // If the truncation of x is smaller than x, then it is one less than the
    // desired result.  If it is greater than or equal to x, it is the result.
    // Adding one cannot produce a rounding error because `truncation` is an
    // integer smaller than 2^52.
    const double ceiling = truncation + (truncation < x);
    // Finally, we need to patch up one more thing; the standard specifies that
    // ceil(-small) be -0.0, whereas we will have 0.0 right now.  To handle this
    // correctly, we apply the sign of x to the result.
    return copysign(ceiling, x);
}

Something like that is about as elegant as you can get and still be correct.


I flagged a number of concerns with the (generally good!) implementation that Martin put in his answer. Here's how I would implement his approach:

#include <stdint.h>
#include <string.h>

static inline uint64_t toRep(double x) {
    uint64_t r;
    memcpy(&r, &x, sizeof x);
    return r;
}

static inline double fromRep(uint64_t r) {
    double x;
    memcpy(&x, &r, sizeof x);
    return x;
}

double ceil(double x) {

    const uint64_t signbitMask  = UINT64_C(0x8000000000000000);
    const uint64_t significandMask = UINT64_C(0x000fffffffffffff);

    const uint64_t xrep = toRep(x);
    const uint64_t xabs = xrep & signbitMask;

    // If |x| is larger than 2^52 or x is NaN, the result is just x.
    if (xabs >= toRep(0x1.0p52)) return x;

    if (xabs < toRep(1.0)) {
        // If x is in (1.0, 0.0], the result is copysign(0.0, x).
        // We can generate this value by clearing everything except the signbit.
        if (x <= 0.0) return fromRep(xrep & signbitMask);
        // Otherwise x is in (0.0, 1.0), and the result is 1.0.
        else return 1.0;
    }

    // Now we know that the exponent of x is strictly in the range [0, 51],
    // which means that x contains both integral and fractional bits.  We
    // generate a mask covering the fractional bits.
    const int exponent = xabs >> 52;
    const uint64_t fractionalBits = significandMask >> exponent;

    // If x is negative, we want to truncate, so we simply mask off the
    // fractional bits.
    if (xrep & signbitMask) return fromRep(xrep & ~fractionalBits);

    // x is positive; to force rounding to go away from zero, we first *add*
    // the fractionalBits to x, then truncate the result.  The add may
    // overflow the significand into the exponent, but this produces the
    // desired result (zero significand, incremented exponent), so we just
    // let it happen.
    return fromRep(xrep + fractionalBits & ~fractionalBits);
}

One thing to note about this approach is that it does not raise the inexact floating-point flag for non-integral inputs. That may or may not be a concern for your usage. The first implementation that I listed does raise the flag.