C++ cmath nearbyint , nearbyintf and nearbyintl function


The C++ <cmath> nearbyint,nearbyintf and nearbyintl round the argument using the current rounding direction.The declaration of the functions are given below.

1 float nearbyint(float x);
2 double nearbyint(double x);
3 long double nearbyint(long double x);
4 float nearbyintf(float x);
5 long double nearbyintl(long double x);

Parameters:
x -The floating point value which is to be rounded off.

Return type
floating point -The nearby integer of the floating point value.

Some points to note:

  i) The rounding is done using the current rounding direction.Simply put if the fractional value is less than 5,the fractional part is dropped and the integer is taken.If the fractional value is equal to or more than 5 than the integer value just next to the value is taken.

  ii) If NAN is passed ‘nan’ is returned.

  iii) If ±∞ is passed ±∞ is returned.

Code example

/*Passing floating point value*/
cout<< “nearbyint( 23.4 )=” << nearbyint( 23.4 ) endl ;
cout<< “nearbyint( 23.56 )=” << nearbyint( 23.56 ) endl ;

/*Passing NAN */
cout<< “nearbyint( NAN )=” << nearbyint( NAN ) endl ;

/*Passing INFINITY */
cout<< “nearbyint( INFINITY )=” << nearbyint( INFINITY ) endl ;

Output

nearbyint( 23.4 )= 23
nearbyint( 23.56 )= 24
nearbyint( NAN )= NAN
nearbyint( INFINITY )= inf



nearbyintf and nearbyintl

*Note

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

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

Code example

#include <typeinfo>

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

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

Output

*nearbyintf
f
f
*nearbyintl
e (means ‘long double’)
e (means ‘long double’)


*Side Note

nearbyint does not raise the ‘inexact’ floating-point exception if the result differs in value from the argument.This is also the difference between rint function which raise the ‘inexact’ floating-point exception if the result differs in value from the argument.


Related links

->C programming nearbyint,nerbyintf and nearbyintl