C++ Standard Library C++ STL Library
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C++ <cfenv> - fegetround() Function



The C++ <cfenv> fegetround() function returns the value of the floating-point rounding macro, as specified in the current floating point environment.

The current rounding mode which reflects the effects of the most recent fesetround, can also be queried with FLT_ROUNDS.

Syntax

int fegetround();

Parameters

No parameter is required.

Return Value

Returns the floating-point rounding macro describing the current rounding direction or a negative value if the direction cannot be determined. All possible rounding direction modes are given below:

MacrosDescription
FE_DOWNWARD Rounding towards negative infinity.
FE_TONEAREST Rounding towards nearest representable value.
FE_TOWARDZERO Rounding towards zero.
FE_UPWARD Rounding towards positive infinity.

Certain library implementations may define additional floating-point rounding direction macro constants (with their corresponding macros also beginning with FE_).

Exception

This function never throws exceptions.

Example:

The example below shows the usage of fegetround() function.

#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<<"rint(10.2): "<<rint(10.2)<<"\n";
  cout<<"rint(10.8): "<<rint(10.8)<<"\n";
  cout<<"rint(-5.2): "<<rint(-5.2)<<"\n";
  cout<<"rint(-5.8): "<<rint(-5.8)<<"\n";

  return 0;
}

The output of the above code will be:

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

❮ C++ <cfenv> Library

5