Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Answer: How do I round a number?

by fundflow (Chaplain)
on Jul 26, 2000 at 00:22 UTC ( #24343=categorized answer: print w/replies, xml ) Need Help??

Q&A > math > How do I round a number? - Answer 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.

Replies are listed 'Best First'.
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):

    Round to nearst tenth (0.1):
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?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2018-05-25 21:31 GMT
Find Nodes?
    Voting Booth?