Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

how to always round up in perl?

by cburger (Acolyte)
on Feb 25, 2011 at 01:54 UTC ( [id://890101]=perlquestion: print w/replies, xml ) Need Help??

cburger has asked for the wisdom of the Perl Monks concerning the following question:

I'm doing a division of a number by 3 and I always want to round to the next greater number. If the result is e.g. 3.3 or 3.6 I want to report 4. Same with 3003.3 etc. How can I do this in perl? Thanks! C

thanks to everyone! it works now :) the oneliners are quite neat.

Replies are listed 'Best First'.
Re: how to always round up in perl?
by toolic (Bishop) on Feb 25, 2011 at 02:03 UTC
    This is a perlfaq:
    perldoc -q round
    POSIX::ceil:
    use warnings; use strict; use POSIX; for (3.3, 3.6, 3003.3) { print $_, "\t", ceil($_), "\n"; } __END__ 3.3 4 3.6 4 3003.3 3004
Re: how to always round up in perl?
by umasuresh (Hermit) on Feb 25, 2011 at 01:59 UTC
Re: how to always round up in perl?
by philipbailey (Curate) on Feb 25, 2011 at 09:10 UTC

    Or if you do not want to import a mass of functions into your namespace from the POSIX module, just do this:

    my $n = 3.3; my $ceiling = int($n + 1);

    (Update) Above is incorrect, as pointed out by others. This works:

    my $ceiling = ($n == int $n) ? $n : int($n + 1);

      That fails if $n is allready an integer. You would need something like:

      my $n = 3.0; my $ceiling = int($n); $ceiling += 1 if $ceiling != $n;

      Or as a one liner:

      my $ceiling = int($n) + ($n != int($n));
        They also fail with negative non-integers.
        perl -MPOSIX=ceil -e "$n=-2.1; print($n, ' POSIX: ', ceil($n))" # -2.1 POSIX: -2 perl -e "$n=-2.1; print($n, ' other: ', int($n) + ($n != int($n)))" # -2.1 other: -1
      if you do not want to import a mass of functions into your namespace from the POSIX module
      ... just do this:
      use warnings; use strict; use POSIX qw(ceil); for (3.3, 3.6, 3003.3) { print $_, "\t", ceil($_), "\n"; } __END__ 3.3 4 3.6 4 3003.3 3004
      According to How to Import, this selectively imports only the ceil function.

      Alternately, you could import nothing and call the function using POSIX::ceil.

      Which I wouldn't recommend, because it fails in the following situation (with $n2) ...
      my $n1 = 3.3; my $n2 = 4; print int($n1 + 1)," ",int($n2 + 1), "\n";

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://890101]
Approved by toolic
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-03-19 02:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found