C++ Standard Library C++ STL Library

C++ <cmath> - nearbyint() Function



The C++ <cmath> nearbyint() function returns an integral value by rounding up the specified number, using the rounding direction specified by fegetround.

This function does not raise FE_INEXACT exceptions. The rint() function is similar to this function, except it may raise FE_INEXACT exceptions if the returned value differs from x.

Syntax

double nearbyint (double x);
float nearbyint (float x);
long double nearbyint (long double x);
double nearbyint (T x);                        

Parameters

x Specify a value to round.

Return Value

Returns an integral value by rounding up the x, using the rounding direction specified by fegetround.

Example:

In the example below, nearbyint() function is used to round the given number.

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

void Rounding_Direction_Message(void) {
  cout<<"Rounding using ";
  switch(fegetround()) {
    case FE_DOWNWARD: 
      cout<<"downward"; break;
    case FE_TONEAREST:   
      cout<<"to-nearest"; break;
    case FE_TOWARDZERO:   
      cout<<"toward-zero"; break;
    case FE_UPWARD:  
      cout<<"upward"; break;
    default:
      cout<<"unknown";
  }
  cout<<" method:"<<endl;
}

int main (){
  Rounding_Direction_Message();

  cout<<"nearbyint(10.2): "<<nearbyint(10.2)<<"\n";
  cout<<"nearbyint(10.8): "<<nearbyint(10.8)<<"\n";
  cout<<"nearbyint(-5.2): "<<nearbyint(-5.2)<<"\n";
  cout<<"nearbyint(-5.8): "<<nearbyint(-5.8)<<"\n";

  return 0;
}

The output of the above code will be:

Rounding using to-nearest method:
nearbyint(10.2): 10
nearbyint(10.8): 11
nearbyint(-5.2): -5
nearbyint(-5.8): -6

❮ C++ <cmath> Library