On May 18, Craig Moynes/Markham/IBM said:

>I looked through my book (perl nutshell) and PP has not arrived yet, so I
>will ask here.
>
>I have an number that needs to be rounded to the nearest whole number.
>This is my solution:

Timothy Kimball has a good solution, but I have a generalization:

  # $rounded = round($num);     # integer
  # $rounded = round($num,2);   # to hundredth's place
  # $rounded = round($num,-1);  # to ten's place

  sub round {
    my ($x, $p) = @_;
    $x ||= 0;
    $p ||= 0;

    (1,-1)[$x < 0] * int( abs($x) * 10**$p + .5 ) / 10**$p;
  }

This technique allows you to round to some place to the left OR right of
the decimal point.  It uses a very simple method: it brings the digit in
the place you want to round IMMEDIATELY to the left of the decimal point:

          v
  round(10234.543, -3);

  10234.543
  1023.4543
  102.34543

It pretends the number is positive (but knows to multiply by -1 if it was
negative).  Then it adds .5 and takes the integer value.  Then, it moves
the digits back to where they started.

  102.34543
 +   .5
 ----------
  102.84543
  102

  10200

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
Are you a Monk?  http://www.perlmonks.com/     http://forums.perlguru.com/
Perl Programmer at RiskMetrics Group, Inc.     http://www.riskmetrics.com/
Acacia Fraternity, Rensselaer Chapter.         Brother #734
*** I need a publisher for my book "Learning Perl Regular Expressions" ***

Reply via email to