Perl-Sensitive Sunglasses PerlMonks

### Answer: How do I round a number?

by fundflow (Chaplain)
 on Jul 26, 2000 at 00:22 UTC 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):

```\$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

Create A New User
Chatterbox?
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
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
World peace can best be achieved by:

Results (191 votes). Check out past polls.

Notices?