nearbyint, nearbyintf, nearbyintl

Header: <math.h>

1-3) Rounds the floating-point argument arg to an integer value in floating-point format, using the current rounding mode.

# Declarations

float nearbyintf( float arg );

(since C99)

double nearbyint( double arg );

(since C99)

long double nearbyintl( long double arg );

(since C99)

#define nearbyint( arg )

(since C99)

# Parameters

# Return value

The nearest integer value to arg, according to the current rounding mode, is returned.

# Notes

The only difference between nearbyint and rint is that nearbyint never raises FE_INEXACT.

The largest representable floating-point values are exact integers in all standard floating-point formats, so nearbyint never overflows on its own; however the result may overflow any integer type (including intmax_t), when stored in an integer variable.

If the current rounding mode is FE_TONEAREST, this function rounds to even in halfway cases (like rint, but unlike round).

# Example

#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
int main(void)
{
// #pragma STDC FENV_ACCESS ON
    fesetround(FE_TONEAREST);
    printf("rounding to nearest:\nnearbyint(+2.3) = %+.1f  ", nearbyint(2.3));
    printf("nearbyint(+2.5) = %+.1f  ", nearbyint(2.5));
    printf("nearbyint(+3.5) = %+.1f\n", nearbyint(3.5));
    printf("nearbyint(-2.3) = %+.1f  ", nearbyint(-2.3));
    printf("nearbyint(-2.5) = %+.1f  ", nearbyint(-2.5));
    printf("nearbyint(-3.5) = %+.1f\n", nearbyint(-3.5));
 
    fesetround(FE_DOWNWARD);
    printf("rounding down: \nnearbyint(+2.3) = %+.1f  ", nearbyint(2.3));
    printf("nearbyint(+2.5) = %+.1f  ", nearbyint(2.5));
    printf("nearbyint(+3.5) = %+.1f\n", nearbyint(3.5));
    printf("nearbyint(-2.3) = %+.1f  ", nearbyint(-2.3));
    printf("nearbyint(-2.5) = %+.1f  ", nearbyint(-2.5));
    printf("nearbyint(-3.5) = %+.1f\n", nearbyint(-3.5));
 
    printf("nearbyint(-0.0) = %+.1f\n", nearbyint(-0.0));
    printf("nearbyint(-Inf) = %+.1f\n", nearbyint(-INFINITY));
}

# See also