Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

How do I round up a number?

( #66948=categorized question: print w/ replies, xml ) Need Help??
Contributed by MrNobo1024 on Mar 25, 2001 at 08:03 UTC
Q&A  > math


Description:

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?

Answer: How do I round up a number?
contributed by Anonymous Monk

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)) }
Answer: How do I round up a number?
contributed by damian1301

Heh, go check out the Math::Round module...probably more efficient.

Answer: How do I round up a number?
contributed by powerman

See all round-like perl functions here.

Answer: How do I round up a number?
contributed by Tiefling

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

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others chanting in the Monastery: (12)
    As of 2014-09-02 20:09 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      My favorite cookbook is:










      Results (29 votes), past polls