nearbyint(), nearbyintf(), nearbyintl() — Round the argument to the nearest integer

Standards

Standards / Extensions C or C++ Dependencies

C99
Single UNIX Specification, Version 3
C++ TR1 C99

both  z/OS V1R7

Format

#define _ISOC99_SOURCE
#include <math.h>

double nearbyint(double x);
float nearbyintf(float x);
long double nearbyintl(long double x);
C++ TR1 C99:
#define _TR1_C99
#include <math.h>

float nearbyint(float x); 
long double nearbyint(long double x);

General description

The nearbyint() family of functions round x to an integer value, in floating-point format, using the current rounding mode without raising the inexact floating-point exception.
Note: The following table shows the viable formats for these functions. See IEEE binary floating-point for more information about IEEE Binary Floating-Point.
Function Hex IEEE
nearbyint X X
nearbyintf X X
nearbyinfl X X

Returned value

If successful, they return the rounded integer value. If the correct value causes an overflow, a range error occurs and the value, respectively, of the macro: +/-HUGE_VAL, +/-HUGE_VALF, or +/-HUGE_VALL (with the same sign as x) is returned.

Example

/*
 * This program illustrates the use of nearbyint() function
 *
 * Note: to get the results shown in this  information, this program
 *       should be compiled using FLOAT(IEEE)
 *
 */
#define _ISOC99_SOURCE
#include <math.h>
#include <stdio.h>
#include <_Ieee754.h>   /* save/get fpc functions   */

char *RoundStr (_FP_rmode_t rm_type) {
  char *RndStr="undetermined";
   switch (rm_type) {
     case (_RMODE_RN):
        RndStr="round to nearest";
        break;
     case (_RMODE_RZ):
        RndStr="round toward zero";
        break;
     case (_RMODE_RP):
        RndStr="round toward +infinity ";
        break;
     case (_RMODE_RM):
        RndStr="round toward -infinity ";
        break;
   }
   return (RndStr);
}


void main() {

  _FP_fpcreg_t save_rmode, current_rmode;
  double       rnd2nearest;
  double       number1=1.5,
               number2=-3.92;

  printf("Illustrates the nearbyint() function\n");
  __fpc_rd(&current_rmode);      /* get current rounding mode */

  rnd2nearest = nearbyint(number1);
  printf ("When rounding direction is %s:\n nearbyint(%.2f) = %f\n",
           RoundStr(current_rmode.rmode),number1, rnd2nearest);
  save_rmode.rmode = _RMODE_RZ;
  __fpc_sm(save_rmode.rmode);    /* set rounding mode to round to zero */

  rnd2nearest = nearbyint(number2);
  printf ("When rounding direction is %s:\n nearbyint(%.2f) = %f\n",
           RoundStr(save_rmode.rmode),number2, rnd2nearest);
}


Output

Illustrates the nearbyint() function
When rounding direction is round to nearest:
 nearbyint(1.50) = 2.000000
When rounding direction is round toward zero:
 nearbyint(-3.91) = -3.000000