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