Join our newsletter for the latest updates.

C++ round()

In this tutorial, we will learn about the round() function in C++ with the help of examples.

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

It is defined in the cmath header file.

Example

#include <iostream>
#include <cmath>
using namespace std;

int main() {

// display integral value closest to 15.5 cout << round(15.5);
return 0; } // Output: 16

round() Syntax

The syntax of round() function is:

round(double num);

round() Parameters

The round() function takes the following parameters:

  • num - a floating-point number which is to be rounded off. It can be of the following types:
    • double
    • float
    • long double

round() Return Value

The round() function returns:

  • the integral value that is nearest to num, with halfway cases rounded away from zero.

round() Prototypes

The prototypes of the round() function as defined in the cmath header file are:

double round(double num);

float round(float num);

long double round(long double num);

// for integral type
double round(T num);

Example 1: C++ round()

#include <iostream>
#include <cmath>
using namespace std;

int main() {

  double num, result;

num = 11.16; result = round(num);
cout << "round(" << num << ") = " << result << endl;
num = 13.87; result = round(num);
cout << "round(" << num << ") = " << result << endl;
num = 50.5; result = round(num);
cout << "round(" << num << ") = " << result; return 0; }

Output

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

Example 2: C++ round() for Negative Numbers

#include <iostream>
#include <cmath>
using namespace std;

int main() {

  double num, result;

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

Output

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

Example 3: C++ round() for Integral Types

#include <iostream>
#include <cmath>
using namespace std;

int main() {
  double result;

int num = 15; result = round(num);
cout << "round(" << num << ") = " << result; return 0; }

Output

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?