Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Answer: How do I round a number?

( #24343=categorized answer: print w/ replies, xml ) Need Help??

Q&A > math > How do I round a number? contributed by fundflow

The guy asked to round a number, the simplest way is (my highschool teacher would be proud now..): $rounded = int ( $orig + 0.5 )
This approach floors any decimal portion less than 0.5, and rounds up (in value) any decimal portion greater than .5. That means the following:
1.1 rounds to 1.0. 1.5 rounds to 2.0. -1.1 rounds to 1.0. -1.5 rounds to 1.0.

Comment on Answer: How do I round a number?
Select or Download Code
RE: Answer: How do i round a generated number in Perl? ...math.round (as in javascript) ...?
by lhoward (Vicar) on Jul 26, 2000 at 00:27 UTC
    This concept presented above can be expanded to round to more (or less) percision than just "round number to nearest integer". i.e.

    Round to nearest hundred (100):

    $rounded=100*int(0.5+$number/100);
    Round to nearst tenth (0.1):
    $rounded=0.1*int(0.5+$number/0.1);
    etc...
Re: Answer: How do I round a number?
by I0 (Priest) on Dec 16, 2000 at 02:38 UTC
    $rounded = int ( $orig + 0.5 ) assumes $rounded is positive.
    More generally:  use POSIX; $rounded = floor ( $orig + 0.5 )
    or $rounded = sprintf( "%.f" , $orig ) to properly handle the half-way case
    See also `perldoc -q round`
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 studying the Monastery: (8)
As of 2014-08-20 13:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (113 votes), past polls