Join our newsletter for the latest updates.

C++ round()

The round() function in C++ returns the integral value that is nearest to the argument, with halfway cases rounded away from zero.

The round() function in C++ returns the integral value that is nearest to the argument, with halfway cases rounded away from zero.


round() prototype [As of C++ 11 standard]

double round(double x);
float round(float x);
long double round(long double x);
double round(T x); // For integral type

The round() function takes a single argument and returns a value of type double, float or long double type. This function is defined in <cmath> header file.


round() Parameters

The round() function takes a single argument value to round.


round() Return value

The round() function returns the integral value that is nearest to x, with halfway cases rounded away from zero.


Example 1: How round() works in C++?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double x = 11.16, result;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;

    x = 13.87;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    x = 50.5;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    x = -11.16;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;

    x = -13.87;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    x = -50.5;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;
    
    return 0;
}

When you run the program, the output will be:

round(11.16) = 11
round(13.87) = 14
round(50.5) = 51
round(-11.16) = -11
round(-13.87) = -14
round(-50.5) = -51

Example 2: round() function for integral types

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int x = 15;
    double result;
    result = round(x);
    cout << "round(" << x << ") = " << result << endl;

    return 0;
}

When you run the program, the output will be:

round(15) = 15

For integral values, applying the round function returns the same value as the input. So it is not commonly used for integral values in practice.

Did you find this article helpful?