http://qs321.pair.com?node_id=66948

MrNobo1024 has asked for the wisdom of the Perl Monks concerning the following question: (math)

int($num) rounds a number down, but there dosen't seem to be any function to round a number up. int($num + 1) works ok for fractional values, but dosen't work right for integers. How can I round numbers up in a way that works for all numbers?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I round up a number?
by Anonymous Monk on Mar 25, 2001 at 08:08 UTC
    Use the POSIX module:
    use POSIX qw(ceil); print ceil(3.5); # prints 4 print ceil(4); # also prints 4
    or, you can use this function:
    sub roundup { my $n = shift; return(($n == int($n)) ? $n : int($n + 1)) }
      roundup(-1.5) is wrong
    Re: How do I round up a number?
    by damian1301 (Curate) on Mar 25, 2001 at 10:28 UTC
      Heh, go check out the Math::Round module...probably more efficient.
    Re: How do I round up a number?
    by powerman (Friar) on Apr 23, 2002 at 11:48 UTC
      See all round-like perl functions here.
    Re: How do I round up a number?
    by Tiefling (Monk) on Jun 11, 2001 at 18:30 UTC
      My preferred answer if you insist on rounding up is the second one given by Anonymous Monk above. However, it's best to round to the nearest integer, in which case int($n+0.5) is your friend.

      Tiefling
        That fails for negative numbers.
    Re: How do I round up a number?
    by Daddio (Chaplain) on Apr 01, 2001 at 19:53 UTC
      Another non-module way is to use sprintf.
      @num = (6, 5.3, 8.5, 9.5000000001, 3.84, 4.51); foreach $num (@num) { print qq{original: $num\n}; $new = sprintf "%.0f\n",$num; print qq{new: $new}; }
      will produce
      original: 6 new: 6 original: 5.3 new: 5 original: 8.5 new: 8 original: 9.5000000001 new: 10 original: 3.84 new: 4 original: 4.51 new: 5
      Not quite right for the 8.5, but it is close for the rest, and that can be compared differently.

      Originally posted as a Categorized Answer.

    Re: How do I round up a number?
    by ar0n (Priest) on Apr 01, 2001 at 22:17 UTC
      While int($num + 1) doesn't work right, int($num) + 1 will. Alternatively, a number of men on horseback can round up large group of numbers fairly efficienty. A well trained dog helps, also.

      Originally posted as a Categorized Answer.

    A reply falls below the community's threshold of quality. You may see it by logging in.