Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

nearbyint — rounding using the current mode

nearbyint returns an integer-valued double using the current rounding direction without raising the inexact exception.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <math.h>
double nearbyint(double x);

nearbyint(x) from <math.h> returns an integer value represented as double, not an integer type. It uses the current rounding direction.

Unlike rint, it does not raise the inexact exception (FE_INEXACT); this does not mean clearing an existing flag. In contrast, round rounds halfway cases away from zero regardless of the current mode.

The example selects FE_DOWNWARD, so -2.5 produces -3.0, then restores the previous mode. It requires compiler and library support for the floating-point environment; a C23 flag alone does not establish that support.

Examples

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

#pragma STDC FENV_ACCESS ON

int main(void)
{
#ifdef FE_DOWNWARD
    int saved = fegetround();
    if (saved < 0 || fesetround(FE_DOWNWARD) != 0)
        return 1;

    volatile double x = -2.5;
    double result = nearbyint(x);

    if (fesetround(saved) != 0)
        return 1;

    printf("%.1f\n", result);
    return 0;
#else
    return 1;
#endif
}

Result

-3.0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources