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
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.
🌐
Cppreference
en.cppreference.com › w › c › numeric › math › floor
floor, floorf, floorl - cppreference.com
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)); }
🌐
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; }
🌐
W3Schools
w3schools.com › c › ref_math_floor.php
C Math floor() Function
The floor() function is defined in the <math.h> header file.
🌐
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; }
🌐
IncludeHelp
includehelp.com › c-programs › floor-and-ceil-functions-of-math-h.aspx
floor() and ceil() functions of math.h in C
#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; }
🌐
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.
🌐
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.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Math › floor
Math.floor() - JavaScript | MDN
*/ 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
🌐
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.
🌐
TutorialsPoint
tutorialspoint.com › home › c_standard_library › c standard library: floor function
C Standard Library: floor Function
August 29, 2012 - Following is the basic C library example to see the demonstration of floor() function. #include <stdio.h> #include <math.h> int main () { float val1, val2, val3, val4; val1 = 1.6; val2 = 1.2; val3 = 2.8; val4 = 2.3; printf("Value1 = %.1lf\n", floor(val1)); printf("Value2 = %.1lf\n", floor(val2)); printf("Value3 = %.1lf\n", floor(val3)); printf("Value4 = %.1lf\n", floor(val4)); return(0); } The above code produces the following result − ·
🌐
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.
🌐
Codecogs
codecogs.com › library › computing › c › math.h › floor.php
floor - Math.h - C - C++ Computing Reference with Worked Examples
#include <math.h> The floor functions return the largest integral value less than or equal to x. Example: 1 · Workings · #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; } Solution ·
🌐
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\).
🌐
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 ...
🌐
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.
🌐
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.
🌐
O'Reilly
oreilly.com › library › view › c-in-a › 0596006977 › re79.html
floor - C in a Nutshell [Book]
December 16, 2005 - #include <math.h> doublefloor( double x ); float floorf( float x ); (C99) long double floorl( long double x ); (C99) The floor() function returns the greatest integer that is less than or equal to its argument.
Authors   Peter PrinzTony Crawford
Published   2005
Pages   618
🌐
GeeksforGeeks
geeksforgeeks.org › c language › c-floor-function
C floor() Function - GeeksforGeeks
July 7, 2024 - To use the floor(x) function, you need to include the math.h library.