round() Function
The round()
function in C returns the integral value nearest to a given floating-point number, rounding halfway cases away from zero. It effectively converts a floating-point number to its nearest integer equivalent, represented as a floating-point value.
Syntax of round()
double round(double x);
float roundf(float x);
long double roundl(long double x);
Parameters
Parameter | Description |
---|---|
x | Value to round. |
Notable aspects of round()
include its behavior of rounding halfway cases away from zero. This ensures that numbers exactly between two integers are rounded to the integer further from zero, providing predictable results.
Return Value
The function returns the rounded value as a floating-point number, even though the value represents an integral result.
Examples for round()
Example 1: Basic Rounding of a Positive Floating-Point Number
This example demonstrates the basic use of round()
to round a positive floating-point number to its nearest integer value.
Program
#include <stdio.h>
#include <math.h>
int main() {
double value = 3.6;
double result = round(value);
printf("Rounded value: %.0f\n", result);
return 0;
}
Explanation:
- The variable
value
is initialized with3.6
. round()
rounds the number to the nearest integer, which is4
.- The result is printed to display the rounded value.
Program Output:
Rounded value: 4
Example 2: Rounding a Negative Floating-Point Number
This example illustrates how round()
handles negative numbers, rounding them away from zero.
Program
#include <stdio.h>
#include <math.h>
int main() {
double value = -2.5;
double result = round(value);
printf("Rounded value: %.0f\n", result);
return 0;
}
Explanation:
- The variable
value
is set to-2.5
. round()
rounds it away from zero, resulting in-3
.- The output is printed to show the rounded negative value.
Program Output:
Rounded value: -3
Example 3: Rounding a Value at the Halfway Point
This example shows how round()
rounds a number that is exactly halfway between two integers by rounding away from zero.
Program
#include <stdio.h>
#include <math.h>
int main() {
double value = 2.5;
double result = round(value);
printf("Rounded value: %.0f\n", result);
return 0;
}
Explanation:
- The variable
value
is initialized with2.5
, which lies exactly halfway between2
and3
. round()
rounds it away from zero, resulting in3
.- The rounded value is printed.
Program Output:
Rounded value: 3
Example 4: Using roundf() for Single-Precision Floating-Point Numbers
This example demonstrates the use of roundf()
, which is tailored for single-precision floating-point numbers.
Program
#include <stdio.h>
#include <math.h>
int main() {
float value = 3.3f;
float result = roundf(value);
printf("Rounded value: %.0f\n", result);
return 0;
}
Explanation:
- A single-precision floating-point variable
value
is initialized with3.3f
. - The
roundf()
function rounds the value to the nearest integer. - The rounded result is printed.
Program Output:
Rounded value: 3