home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!cis.ohio-state.edu!ucbvax!cgl!pooh.mmwb.ucsf.edu!nomi
- From: nomi@pooh.mmwb.ucsf.edu (Nomi Harris)
- Newsgroups: comp.lang.perl
- Subject: Truncating or rounding "floats"
- Message-ID: <nomi.712368419@pooh.mmwb.ucsf.edu>
- Date: 29 Jul 92 00:06:59 GMT
- Sender: news@cgl.ucsf.edu (USENET News System)
- Organization: UCSF Computer Graphics Lab
- Lines: 44
-
- 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:
-
- # Round off a "float" to an "int"
- sub round {
- local($float) = @_;
- local($int, $remainder);
-
- $int = $float;
- $int =~ s/\..*//; # Truncate by getting rid of digits that
- # follow the decimal point
-
- $remainder = $float - $int;
- if ($remainder >= 0.5) {
- $int++; # Round up
- }
-
- return($int);
- }
-
-
- Although the "int" this function returned looked like what I wanted,
- it seemed to behave like the original float when I used it in arithmetic
- expressions! I added the following lines before return($int):
-
- print("Round($float) = $int.\n");
- $int = $int * 1;
- print("After multiplying by 1: $int.\n");
- return($int);
-
- Lo and behold, the value of the "int" reverted to the float after I
- multiplied it by 1! Apparently, the string substitution I did on $int
- changed its printed appearance without actually changing the value.
- Weird!
-
- I also tried sprintf(), but that didn't work either, probably for the
- same reason.
-
- Any suggestions?
-
- Nomi Harris
- nomi@cgl.ucsf.edu
-