floor() Function

The floor() function in C rounds a given value downward to the nearest integral value, effectively reducing the number to the next lower whole number if it is not already an integer. This operation is useful for converting floating-point numbers into whole numbers in a predictable manner.


Syntax of floor()

</>
Copy
double floor(double x);
float  floorf(float x);
long double floorl(long double x);

Parameters

ParameterDescription
xThe value to be rounded down.

The function returns the largest integer value that is not greater than the provided value, and the result is of the same floating-point type as the input. It is important to note that even if the input value is already an integer, it is still returned as a floating-point number.


Examples for floor()

Example 1: Rounding Down a Positive Floating-Point Number

This example demonstrates how floor() rounds a positive number downward.

Program

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

int main() {
    double num = 3.7;
    double result = floor(num);

    printf("Original number: %.2f\n", num);
    printf("After applying floor(): %.2f\n", result);
    return 0;
}

Explanation:

  1. A double variable num is initialized with the value 3.7.
  2. The floor() function is applied to num to round it down to the nearest whole number, resulting in 3.0.
  3. The original and the rounded values are printed to the console.

Program Output:

Original number: 3.70
After applying floor(): 3.00

Example 2: Rounding Down a Negative Floating-Point Number

This example demonstrates how floor() behaves when applied to a negative number, rounding it downward to a more negative integer.

Program

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

int main() {
    double num = -3.2;
    double result = floor(num);

    printf("Original number: %.2f\n", num);
    printf("After applying floor(): %.2f\n", result);
    return 0;
}

Explanation:

  1. A double variable num is initialized with the value -3.2.
  2. The floor() function is applied to num, which rounds it down to -4.0 because -4 is the largest integer less than -3.2.
  3. The original and the rounded values are printed to the console.

Program Output:

Original number: -3.20
After applying floor(): -4.00