nearbyint() function in C++ with examples

In this tutorial, we are going to learn about the nearbyint() function in C++. This C++ function is defined in <cmath> header file.

As the name suggests, the nearbyint() function can be used in a C++ program to find the nearby integer value for a given number using the current rounding mode. The current rounding mode is based on fesetround() function.

The syntax for nearbyint() function has been given here.

float nearbyint(float x);

double nearbyint(double x);

long double nearbyint(long double x);

The function returns the rounded value for the number passed as a parameter. We can use fesetround() function to manipulate the return value for this function.

Let us understand its working with a few examples.

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

int main()
{
  float num1 = 9.8;
  double num2 = 5.3;
  long double num3 = -6.9;
  
  cout << "num1 = " <<num1 << endl;
  cout << "num2 = " <<num2 << endl;
  cout << "num3 = " <<num3 << endl;
  
  cout << "Near by integer(num1) = " << nearbyint(num1) << endl;
  cout << "Near by integer(num2) = " << nearbyint(num2) << endl;
  cout << "Near by integer(num3) = " << nearbyint(num3) << endl;
  
  return 0;
}

Output:

num1 = 9.8
num2 = 5.3
num3 = -6.9
Near by integer(num1) = 10
Near by integer(num2) = 5
Near by integer(num3) = -7

As you can see from the output, all the values passed in nearbyint() function are rounded to their nearby integer. Here, have a look at another example.

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

int main()
{
  float num1 = 9.8;
  double num2 = 5.3;
  long double num3 = -6.9;
  
  cout << "num1 = " <<num1 << endl;
  cout << "num2 = " <<num2 << endl;
  cout << "num3 = " <<num3 << endl;
  
  fesetround(FE_UPWARD);
  
  cout << "Near by integer(num1) = " << nearbyint(num1) << endl;
  cout << "Near by integer(num2) = " << nearbyint(num2) << endl;
  cout << "Near by integer(num3) = " << nearbyint(num3) << endl;
  
  return 0;
}

Output:

num1 = 9.8
num2 = 5.3
num3 = -6.9
Near by integer(num1) = 10
Near by integer(num2) = 6
Near by integer(num3) = -6

In the above program, we have used fesetround() function to set the rounding mode to upward. The nearbyint() function here returns the nearby upward value. Similarly, we can use fesetround(FE_DOWNWARD) to set the rounding mode to downward.

Thank you.

Also read: Use remquo() math function in C++

Leave a Reply

Your email address will not be published. Required fields are marked *