Both of your attempts have limitations:

  • If the double value is outside the range of the int type, converting to int is implementation defined.
  • If the double value is negative but integral, returning (int)num - 1 is incorrect.

Here is an (almost) portable version that tries to handle all cases:

double my_floor_2(double num) {
    if (num >= LLONG_MAX || num <= LLONG_MIN || num != num) {
        /* handle large values, infinities and nan */
        return num;
    }
    long long n = (long long)num;
    double d = (double)n;
    if (d == num || num >= 0)
        return d;
    else
        return d - 1;
}

It should be correct if type long long has more value bits than type double, which is the case on most modern systems.

Answer from chqrlie on Stack Overflow

Both of your attempts have limitations:

  • If the double value is outside the range of the int type, converting to int is implementation defined.
  • If the double value is negative but integral, returning (int)num - 1 is incorrect.

Here is an (almost) portable version that tries to handle all cases:

double my_floor_2(double num) {
    if (num >= LLONG_MAX || num <= LLONG_MIN || num != num) {
        /* handle large values, infinities and nan */
        return num;
    }
    long long n = (long long)num;
    double d = (double)n;
    if (d == num || num >= 0)
        return d;
    else
        return d - 1;
}

It should be correct if type long long has more value bits than type double, which is the case on most modern systems.

Answer from chqrlie on Stack Overflow
🌐
Cppreference
en.cppreference.com › w › c › numeric › math › floor
floor, floorf, floorl - cppreference.com
May 23, 2024 - The largest representable floating-point values are exact integers in all standard floating-point formats, so this function never overflows on its own; however the result may overflow any integer type (including intmax_t), when stored in an integer variable. ... #include <math.h> #include <stdio.h> int main(void) { printf("floor(+2.7) = %+.1f\n", floor(2.7)); printf("floor(-2.7) = %+.1f\n", floor(-2.7)); printf("floor(-0.0) = %+.1f\n", floor(-0.0)); printf("floor(-Inf) = %+f\n", floor(-INFINITY)); }
Top answer
1 of 5
7

Both of your attempts have limitations:

  • If the double value is outside the range of the int type, converting to int is implementation defined.
  • If the double value is negative but integral, returning (int)num - 1 is incorrect.

Here is an (almost) portable version that tries to handle all cases:

double my_floor_2(double num) {
    if (num >= LLONG_MAX || num <= LLONG_MIN || num != num) {
        /* handle large values, infinities and nan */
        return num;
    }
    long long n = (long long)num;
    double d = (double)n;
    if (d == num || num >= 0)
        return d;
    else
        return d - 1;
}

It should be correct if type long long has more value bits than type double, which is the case on most modern systems.

2 of 5
5

No, you can't tackle it this way. The best way of writing your own implementation is to take the one from the C Standard Library on your platform. But note that might contain platform specific nuances so might not be portable.

The C Standard Library floor function is typically clever in that it doesn't work by taking a conversion to an integral type. If it did then you'd run the risk of signed integer overflow, the behaviour of which is undefined. (Note that the smallest possible range for an int is -32767 to +32767).

The precise implementation is also dependent on the floating point scheme used on your platform.

For a platform using IEEE754 floating point, and a long long type you could adopt this scheme:

  1. If the magnitude of the number is greater than 253, return it (as it's already integral).
  2. Else, cast to a 64-bit type (long long), and return it back.
🌐
W3Schools
w3schools.com › c › ref_math_floor.php
C Math floor() Function
The floor() function is defined in the <math.h> header file.
🌐
TechOnTheNet
techonthenet.com › c_language › standard_library_functions › math_h › floor.php
C Language: floor function (Floor)
In the C Language, the required header for the floor function is: ... /* Example using floor 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 floor of */ value = 1.6; /* Calculate the floor of value */ result = floor(value); /* Display the result of the calculation */ printf("The floor of %f is %f\n", value, result); return 0; }
🌐
Programiz
programiz.com › c-programming › library-function › math.h › floor
C floor() - C Standard Library
The function prototypes for the long double and float versions of the floor() function are: long double floorl(long double arg); float floorf(float arg); #include <stdio.h> #include <math.h> int main() { double num = -8.33; double result = floor(num); printf("Floor integer of %.2f = %.0f", num, result); return 0; }
🌐
Wolfram MathWorld
mathworld.wolfram.com › FloorFunction.html
Floor Function -- from Wolfram MathWorld
September 27, 2013 - The floor function , also called the greatest integer function or integer value (Spanier and Oldham 1987), gives the largest integer less than or equal to . The name and symbol for the floor function were coined by K. E. Iverson (Graham et al.
🌐
IncludeHelp
includehelp.com › c-programs › floor-and-ceil-functions-of-math-h.aspx
floor() and ceil() functions of math.h in C
March 17, 2018 - #include <stdio.h> //to use 'floor()' function #include <math.h> int main() { // set the type of variable float number, a; // message for user printf("Please enter a number from keyboard to round it up\n"); scanf("%f", &number); // storing the round up value a = floor(number); // printing the calculated value printf("Calculated round up number is : %.2f\n", a); return 0; }
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Math › floor
Math.floor() - JavaScript - MDN Web Docs
*/ function decimalAdjust(type, value, exp) { type = String(type); if (!["round", "floor", "ceil"].includes(type)) { throw new TypeError( "The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.", ); } exp = Number(exp); value = Number(value); if (exp % 1 !== 0 || Number.isNaN(value)) { return NaN; } else if (exp === 0) { return Math[type](value); } const [magnitude, exponent = 0] = value.toString().split("e"); const adjustedValue = Math[type](`${magnitude}e${exponent - exp}`); // Shift back const [newMagnitude, newExponent = 0] = adjustedValue.toString().split("e"); return
🌐
Vultr
docs.vultr.com › clang › standard-library › math-h › floor
C math.h floor() - Round Down to Integer | Vultr Docs
September 27, 2024 - The floor() function, defined in the C standard library math.h, enables rounding down of floating-point numbers to the nearest integer less than or equal to the original number.
🌐
TutorialsPoint
tutorialspoint.com › c_standard_library › c_function_floor.htm
C library - floor() function
Here, we generate the table of integer using floor() and this table ranges of positive floating-point numbers. #include <stdio.h> #include <math.h> int main() { double start = 6.5; double end = 9.5; printf("Table of Floor Integers:\n"); for (double num = start; num <= end; num += 1.0) { double result = floor(num); printf("Floor(%.2lf) = %.0lf\n", num, result); } return 0; }
🌐
Programming Simplified
programmingsimplified.com › c › math.h › floor
floor function | Programming Simplified
Home » C programming » math.h » floor function · Floor function returns the greatest integer not greater than x. For example, if the input is 2.25 then the output will be 2.00.
🌐
Scaler
scaler.com › home › topics › floor() in c
floor() Function in C - Scaler Topics
June 16, 2024 - The floor() is a library function in C defined in the <math.h> header file. This function returns the nearest integer value, which is less than or equal to the floating point number (float or double) passed to it as an argument.
🌐
Cplusplus
cplusplus.com › reference › cmath › floor
Floor
double floor (double x); float floor (float x);long double floor (long double x); double floor (T x); // additional overloads for integral types ... Rounds x downward, returning the largest integral value that is not greater than x. Header <tgmath.h> provides a type-generic macro version of this function.
🌐
Brilliant
brilliant.org › wiki › floor-function
Floor Function | Brilliant Math & Science Wiki
The best way to learn math and computer science. Log in with Google Log in with Facebook Log in with email ... Already have an account? Log in here. ... The floor function (also known as the greatest integer function) \(\lfloor\cdot\rfloor: \mathbb{R} \to \mathbb{Z}\) of a real number \(x\) denotes the greatest integer less than or equal to \(x\).
🌐
Codecogs
codecogs.com › library › computing › c › math.h › floor.php
floor - Math.h - C - C++ Computing Reference with Worked Examples
February 22, 2012 - The floor functions return the largest integral value less than or equal to x. ... #include <stdio.h> #include <math.h> int main(void) { for (double a = 12.5; a < 13.4; a += 0.1) printf("floor of %.1lf is %.1lf\n", a, floor(a)); return 0; }
🌐
Fresh2Refresh
fresh2refresh.com › home › c programming tutorial › c – arithmetic functions › c – floor() function
C floor() function | C Arithmetic functions | Fresh2Refresh
September 23, 2020 - floor( ) function in C returns the nearest integer value which is less than or equal to the floating point argument passed to this function. ”math.h” header file supports floor( ) function in C language.
🌐
CK-12 Foundation
ck12.org › all subjects › algebra i › graphs of functions and non-functions › what is the floor function in maths?
What is the floor function in maths? - Definition | CK-12 Foundation
September 11, 2025 - The greatest integer function, also known as the step function or floor function, is a type of mathematical function. It is denoted by @$\begin{align*}⌊x⌋.\end{align*}@$. The function rounds down a real number to the largest integer less than or equal to the number.
🌐
Cuemath
cuemath.com › algebra › floor-and-ceiling-function
Floor Function and Ceiling Function - Definition, Formulas, Properties, Examples
The measure of the floor function and the ceiling function is based on the output value of the function. For a function x = 5.6, we have the floor function value of \(\lfloor x \rfloor \) = 5, and the ceiling function value as \(\lceil x \rceil \) = 6. ... Boost math skills with daily fun ...
🌐
GeeksforGeeks
geeksforgeeks.org › mathematics › floor-function
Floor Function - GeeksforGeeks
July 23, 2025 - The floor function is a mathematical function that returns the greatest integer less than or equal to a given number. In other words, it rounds a real number down to the largest integer less than or equal to the given number.