Namespaces
Variants
Views
Actions

trunc

From cppreference.com
< c‎ | numeric‎ | math
 
 
 
Common mathematical functions
Functions
Basic operations
(C99)
(C99)
(C99)
(C99)
(C99)
(C99)(C99)(C99)
Exponential functions
(C99)
(C99)
(C99)
(C99)
Power functions
(C99)
(C99)
Trigonometric and hyperbolic functions
(C99)
(C99)
(C99)
Error and gamma functions
(C99)
(C99)
(C99)
(C99)
Nearest integer floating point operations
(C99)(C99)(C99)
trunc
(C99)
(C99)(C99)(C99)
Floating point manipulation functions
(C99)(C99)
(C99)
(C99)
Classification
(C99)
(C99)
(C99)
Macro constants
 
Defined in header <math.h>
float       truncf( float arg );
(since C99)
double      trunc( double arg );
(since C99)
long double truncl( long double arg );
(since C99)

Computes nearest integer not greater in magnitude than arg.

Contents

[edit] Parameters

arg - floating point value

[edit] Return value

Nearest integer not greater in magnitude than arg.

[edit] Notes

The integer value can be always represented by the given floating point type.

[edit] Example

#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <fenv.h>
#include <string.h>
 
#pragma STDC FENV_ACCESS ON
 
void show_fe_exceptions(void)
{
    printf("current exceptions raised: ");
    if(fetestexcept(FE_DIVBYZERO))     printf(" FE_DIVBYZERO");
    if(fetestexcept(FE_INEXACT))       printf(" FE_INEXACT");
    if(fetestexcept(FE_INVALID))       printf(" FE_INVALID");
    if(fetestexcept(FE_OVERFLOW))      printf(" FE_OVERFLOW");
    if(fetestexcept(FE_UNDERFLOW))     printf(" FE_UNDERFLOW");
    if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
    printf("\n");
}
 
int main(void)
{
    printf("trunc(+2.4)      = %+.1f\n", trunc(+2.4));
    printf("trunc(-2.4)      = %+.1f\n", trunc(-2.4));
    printf("trunc(+0.0)      = %+.1f\n", trunc(+0.0));
    printf("trunc(-0.0)      = %+.1f\n", trunc(-0.0));
    printf("trunc(+INFINITY) = %+f\n",   trunc(+INFINITY));
    printf("trunc(-INFINITY) = %+f\n",   trunc(-INFINITY));
    printf("trunc(NAN)       = %f\n",    trunc(NAN));
    printf("\n");
 
    /* no "inexact" floating-point exception for finite non-integer arguments */
    errno = 0; feclearexcept(FE_ALL_EXCEPT);
    printf("trunc(2.4)       = %.1f\n", trunc(2.4));
    printf("%s\n",strerror(errno));
    show_fe_exceptions();
 
    return 0;
}

Possible output:

trunc(+2.4)      = +2.0
trunc(-2.4)      = -2.0
trunc(+0.0)      = +0.0
trunc(-0.0)      = -0.0
trunc(+INFINITY) = +inf
trunc(-INFINITY) = -inf
trunc(NAN)       = nan
 
trunc(2.4)       = 2.0
Success
current exceptions raised:  none

[edit] See also

nearest integer not greater than the given value
(function) [edit]
nearest integer not less than the given value
(function) [edit]
(C99)(C99)(C99)
nearest integer, rounding away from zero in halfway cases
(function) [edit]