C++ cmath round , roundf and roundl function


The C++ <cmath> round,roundf and roundl function return the rounded integer value in floating-point format.The declaration of the functions are given below.

1 float round(float x);
2 double round(double x);
3 long double round(long double x);
4 double roundf(float x);
5 long double roundl(long double x);

Parameters:
x -A floating point value to be rounded off.

Return type
floating point -A rounded integer value.

Some points to note:

i) A round function round the argument halfway cases away from zero regardless of the current rounding direction.

ii) Passing ±0 returns ±0.

iii) Passing NAN returns ‘nan’.

iv) Passing ±∞ returns ±∞.

Code example

/*Passing floating point value*/
cout&l;t< “round(2.5)=” << round( 2.5 ) << endl ;
cout&l;t< “round( -3e-12)=” << round( -3e-12 ) << endl ;

/*Passing NAN */
cout&l;t< “round(NAN)=” << round( NAN ) << endl ;

/*Passing INFINITY */
cout&l;t< “round(INFINITY)=” << round(INFINITY) << endl ;

Output

round(2.5)= 3
round( -3e-12 )= -0
round(NAN)= nan
round(INFINITY)= inf





roundf and roundl

*Note

i)The 4th version roundf is same as the 1st version float round(float).The last character ‘f‘ in ’roundf’ stands for ‘float’ which signify the argument and return type of the function.

ii)The 5th version roundl is same as the 3rd version long double round(long double).The last character ‘l‘ in ’roundl’ stands for ‘long double’ which signify the argument and return type of the function.

Code example

#include <typeinfo>

/*roundf */
cout<< “*roundf\n”;
float f=2;
cout<< typeid( roundf(2) ).name() << endl /*identify type of roundf returned value */
<< typeid( round(f) ).name() << endl; /*identify type of round(float) returned value */

/*roundl*/
cout<< “*roundl\n”;
long double ld=2;
cout<< typeid( roundl(2) ).name() << endl /*indentify type of roundl returned value */
<< typeid( round(ld) ).name() << endl; /*identify type of round(long double) returned value*/

Output

*roundf
f
f
*roundl
e (means ‘long double’)
e (means ‘long double’)


*Side Note

The double function may be written as

#include <math.h>
#include <fenv.h>

#pragma STDC FENV_ACCESS ON

double round( double x )
{
double result;
fenv_t save_env;
feholdexcept( &save_env );
result = rint( x );
if ( fetestexcept(FE_INEXACT) )
{
fesetround( FE_TOWARDZERO );
result = rint( copysign( 0.5 + fabs( x ) , x ));
}

feupdateenv( &save_env);
return result ;

}