C++ cmath trunc,truncf and truncl function


The C++ <cmath> trunc,truncf and truncl function round the argument to integer but not larger in magnitude than the argument.The declaration of the functions are given below.

1 float trunc(float x);
2double trunc(double x);
3 long double trunc(long double x);
4 float truncf(float x);
5blong double truncl(long double x);

Parameters:
x -The argument to be rounded off.

Return type
floating point -The rounded value.

Some points to note:

i) The trunc function always round toward 0.

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

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

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

Code example

/*Passing floating point value*/
cout<< “trunc( 45.67 )=” << trunc( 45.67 ) << endl ;
cout<< “trunc( -.79 )=” << trunc( -.79 ) << endl ;

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

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

Output

trunc( 45.67 )= 45
trunc( -.79 )= -0
trunc( NAN )= nan
trunc( INFINITY )= inf





truncf and truncl

*Note

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

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

Code example

#include <typeinfo>

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

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

Output

*truncf
f
f
*truncl
e (means ‘long double’)
e (means ‘long double’)


Related links

->C programming trunc,truncf and truncl math.h