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

Re: How do I round a number?

by fundflow (Chaplain)
on Jul 26, 2000 at 00:22 UTC ( [id://24343]=note: print w/replies, xml ) Need Help??


in reply to How do I round a number?

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):

    $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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://24343]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-03-29 10:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found