Name

rint

Synopsis

Rounds a floating-point number to an integer value

#include <math.h>
doublerint( double x );
float rintf( float x );
long double rintl( long double x );

The rint() functions round a floating-point number to the next integer value in the current rounding direction. The current rounding direction is an attribute of the floating-point environment that you can read and modify using the fegetround() and fesetround() functions. The rint() functions are similar to the nearbyint() functions, except that the rint() functions may raise the FE_INEXACT exception (depending on the implementation) when the result of the rounding is different from the argument.

Example

struct round_modes { int id; char *str; }  arrModes[ ] =
{
  #ifdef FE_TONEAREST
   { FE_TONEAREST, "FE_TONEAREST: round to nearest representable value" },
  #endif
  #ifdef FE_DOWNWARD
   { FE_DOWNWARD, "FE_DOWNWARD: round toward -Inf" },
  #endif
  #ifdef FE_UPWARD
   { FE_UPWARD, "FE_UPWARD: round toward +Inf" },
  #endif
  #ifdef FE_TOWARDZERO
   { FE_TOWARDZERO, "FE_TOWARDZERO: round toward 0" }
  #endif
};

int nModes = sizeof( arrModes) / sizeof(*arrModes);

 #pragma STDC FENV_ACCESS ON

for ( int i = 0; i < nModes; ++i)
{
  if ( fesetround( arrModes[i].id) != 0)
    break;
  printf( "Current rounding mode: %s\n", arrModes[i].str );

  printf( "rint(1.4)  = %4.1f    rint(1.5)  = %4.1f\n",
          rint(1.4), rint(1.5) );
  printf( "rint(-1.4) = %4.1f    rint(-1.5) = %4.1f\n",
          rint(-1.4), rint(-1.5) );
}

If the implementation supports all four rounding modes, this code produces ...

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.