On Jul 12, Jorge Almeida said:

Is there some way to really round a number to a given number of digits
after the point?

sprintf doesn't seem to work:

        $ perl -e '$a=11.45; $a=sprintf("%.1f", $a); print $a;'
        11.4

From what you learned in math class, sprintf() does it wrong in some
cases.  But Perl's sprintf() just does what C's sprintf() does:

  1.5 -> 2
  2.5 -> 2
  3.5 -> 4
  4.5 -> 4

It's weird. Suffice to say, here's a rounding function that behaves like you learned about in math class:

  sub round {
    my ($n, $places) = @_;
    my $factor = 10 ** ($places || 0);
    return int(($n * $factor) + ($n < 0 ? -1 : 1) * 0.5) / $factor;
  }

The first argument is the number to round, and the second argument is the number of places after the decimal point to round to.

  round(123.456,-2) --> 100
  round(123.456,-1) --> 120
  round(123.456)    --> 123
  round(123.456,0)  --> 123
  round(123.456,1)  --> 123.5
  round(123.456,2)  --> 123.46

It works with positive and negative numbers (both as the numbers BEING rounded and the places to round TO).

--
Jeff "japhy" Pinyan         %  How can we ever be the sold short or
RPI Acacia Brother #734     %  the cheated, we who for every service
http://japhy.perlmonk.org/  %  have long ago been overpaid?
http://www.perlmonks.org/   %    -- Meister Eckhart

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to