home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / perl / 5008 < prev    next >
Encoding:
Internet Message Format  |  1992-07-28  |  1.6 KB

  1. Path: sparky!uunet!cis.ohio-state.edu!ucbvax!cgl!pooh.mmwb.ucsf.edu!nomi
  2. From: nomi@pooh.mmwb.ucsf.edu (Nomi Harris)
  3. Newsgroups: comp.lang.perl
  4. Subject: Truncating or rounding "floats"
  5. Message-ID: <nomi.712368419@pooh.mmwb.ucsf.edu>
  6. Date: 29 Jul 92 00:06:59 GMT
  7. Sender: news@cgl.ucsf.edu (USENET News System)
  8. Organization: UCSF Computer Graphics Lab
  9. Lines: 44
  10.  
  11. This is probably a silly thing to even try to do in an untyped
  12. language, but I want to round off a "float" variable to an "int."
  13. Since there are no round() or truncate() functions, I wrote my
  14. own function:
  15.  
  16. # Round off a "float" to an "int"
  17. sub round {
  18.      local($float) = @_;
  19.      local($int, $remainder);
  20.      
  21.      $int = $float;
  22.      $int =~ s/\..*//;    # Truncate by getting rid of digits that
  23.             # follow the decimal point
  24.  
  25.      $remainder = $float - $int;
  26.      if ($remainder >= 0.5) {
  27.       $int++;    # Round up
  28.      }
  29.  
  30.      return($int);
  31. }
  32.  
  33.  
  34. Although the "int" this function returned looked like what I wanted,
  35. it seemed to behave like the original float when I used it in arithmetic
  36. expressions!  I added the following lines before  return($int):
  37.  
  38.      print("Round($float) = $int.\n");
  39.      $int = $int * 1;
  40.      print("After multiplying by 1: $int.\n");
  41.      return($int);
  42.  
  43. Lo and behold, the value of the "int" reverted to the float after I
  44. multiplied it by 1!  Apparently, the string substitution I did on $int
  45. changed its printed appearance without actually changing the value.
  46. Weird!
  47.  
  48. I also tried sprintf(), but that didn't work either, probably for the
  49. same reason.
  50.  
  51. Any suggestions?
  52.  
  53.     Nomi Harris
  54.     nomi@cgl.ucsf.edu
  55.