home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_02_06 / 2n06076a < prev    next >
Text File  |  1991-04-16  |  998b  |  40 lines

  1.  
  2.      double tonearest(double x)
  3.          {
  4.          double i, f, dummy;
  5.      
  6.          /* break x into fractional and integral parts */
  7.          f = fabs(modf(x,&i));
  8.      
  9.          /* if no fractional part, return integer part */
  10.          if (f == 0.0)
  11.              return i;
  12.      
  13.          /* check for a fraction of 1/2 */
  14.          if (f == 0.5)
  15.              {
  16.              /* if i isn't even, set i to nearest even */
  17.              if (modf(i / 2.0, &dummy) != 0.0)
  18.                  {
  19.                  if (x < 0.0)
  20.                      i -= 1.0;
  21.                  else
  22.                      i += 1.0;
  23.                  }
  24.              }
  25.          else
  26.              {
  27.              /* if fraction is greater than 1/2, round i up */
  28.              if (f > 0.5)
  29.                  {
  30.                  if (x < 0.0)
  31.                      i -= 1.0;
  32.                  else
  33.                      i += 1.0;
  34.                  }
  35.              }
  36.      
  37.          return i;
  38.          }
  39.  
  40.