We don't bite newbies here... much 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? - 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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (11)
As of 2016-07-01 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What is your favorite alternate name for a (specific) keyboard key?

Results (6 votes). Check out past polls.