C++ fesetround()

The fesetround() function in C++ attempts to set the specified floating point rounding direction which is expected to be one of the floating point rounding macros.

The fesetround() function is defined in <cfenv> header file.

fesetround() prototype

int fesetround( int round );

This function takes a single argument round, which is one of the floating point rounding macros. It then attempts to set round as the floating point rounding direction.


fesetround() Parameters

  • round: Rounding direction which is one of floating point rounding macros. The possible values for round are FE_TONEAREST, FE_DOWNWARD, FE_UPWARD, FE_TOWARDZERO.

fesetround() Return value

  • On success, the fesetround() function returns 0.
  • On failure, it returns nonzero.

Example: How fesetround() function works?

#include <iostream>
#include <cmath>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
using namespace std;

void print_current_rounding_direction()
{
	cout << "Current rounding method: ";
	switch (fegetround()) {
		case FE_TONEAREST:
			cout << "FE_TONEAREST";
			break;
		case FE_DOWNWARD:
			cout << "FE_DOWNWARD";
			break;
		case FE_UPWARD:
			cout << "FE_UPWARD";
			break;
		case FE_TOWARDZERO:
			cout << "FE_TOWARDZERO";
			break;
		default:
			cout << "unknown";
	};
	cout << endl;
}

int main()
{
	print_current_rounding_direction();
	cout << "6.2 -> " << rint(6.2) << endl;
	cout << "18.7 -> " << rint(18.7) << endl;

	fesetround(FE_UPWARD);
	print_current_rounding_direction();
	cout << "6.2 -> " << rint(6.2) << endl;
	cout << "19.7 -> " << rint(19.7) << endl;
	
	fesetround(FE_DOWNWARD);
	print_current_rounding_direction();
	cout << "6.2 -> " << rint(6.2) << endl;
	cout << "19.7 -> " << rint(19.7) << endl;
	
	return 0;
}

When you run the program, the output will be:

Current rounding method: FE_TONEAREST
6.2 -> 6
18.7 -> 19
Current rounding method: FE_UPWARD
6.2 -> 7
19.7 -> 20
Current rounding method: FE_DOWNWARD
6.2 -> 6
19.7 -> 19