home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / perl / 5011 < prev    next >
Encoding:
Text File  |  1992-07-28  |  1.7 KB  |  41 lines

  1. Newsgroups: comp.lang.perl
  2. Path: sparky!uunet!zaphod.mps.ohio-state.edu!caen!umeecs!umn.edu!s6.math.umn.edu!rantapaa
  3. From: rantapaa@s6.math.umn.edu (Erik E. Rantapaa)
  4. Subject: Re: Truncating or rounding "floats" and bug with ($_==int?2:3)
  5. Message-ID: <rantapaa.712384725@s6.math.umn.edu>
  6. Sender: news@news2.cis.umn.edu (Usenet News Administration)
  7. Nntp-Posting-Host: s6.math.umn.edu
  8. Organization: University of Minnesota
  9. References: <nomi.712368419@pooh.mmwb.ucsf.edu>
  10. Date: Wed, 29 Jul 1992 04:38:45 GMT
  11. Lines: 28
  12.  
  13. nomi@pooh.mmwb.ucsf.edu (Nomi Harris) writes:
  14.  
  15. >This is probably a silly thing to even try to do in an untyped
  16. >language, but I want to round off a "float" variable to an "int."
  17. >Since there are no round() or truncate() functions, I wrote my
  18. >own function:
  19.  
  20. Perl has int() which according to the man page returns the 'integer portion'
  21. of an expression.  Unfortunately, neither the man page nor the Camel book
  22. clarifies what this means.  From experimentation, it seems that int(x) returns
  23. the floor of x if x >= 0 and ceiling of x for x < 0.  Given that, you can
  24. use the following routines:
  25.  
  26. sub floor   { ($_)=@_; ( $_ < 0 ? ( $_==int($_) ? $_ : -int(-$_+1)) : int ); }
  27. sub ceiling { ($_)=@_; ( $_ < 0 ? int : ( $_==int($_) ? $_ : -int(-$_-1)) ); }
  28. sub closest { ($_)=@_; ( $_ < 0 ? int($_-0.5) : int($_+0.5) ); }
  29.  
  30. Note &closest(1.5) == 2 and &closest(-3.5) = -4 which may or may not
  31. be what you want.
  32.  
  33. BTW, the following gives a syntax error (SunOS, patchlevel 19):
  34.  
  35. ( $_==int ? 2 : 3)
  36. --
  37.         Erik Rantapaa                   rantapaa@math.umn.edu
  38.  The use of COBOL cripples the mind; its teaching should, therefore, be
  39.  regarded as a criminal offense.
  40.          -- E. W. Dijkstra
  41.