Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to do round, roundup and rounddown in Perl

Status
Not open for further replies.

ghung

Technical User
Oct 24, 2003
7
FI
Hi Folks,

I am new in Perl and in this forum. I would like to round my decimal number to the nearest integer but I couldn't find such kind of built-in function in perl. Also how about roundup and rounddown? Any comment is highly appreciated.

Many thanks!

Gary
 
from Perl Cookbook (p46,47)

Code:
#!/usr/bin/perl
use POSIX;
print "Number\tInt\tFloor\tCeil\tRounded\n";
@array = (3.352, 3.545, 3.725, -3.336);
foreach (@array) {
  printf ( "%.3f\t%.2f\t%.2f\t%.2f\t%.2f\n", $_, int($_), floor($_), ceil($_), sprintf("%.2f",$_));
}

The printf function is just for formatting the output, sprintf rounds up. For more rounding have a look at the math libraries on search.cpan.org.

HTH
--Paul
 
I think someone mentioned in another thread here a while back that the fastest way to round is to add .5 then use int()

foreach (@array){
$rounded = int($_+.5);
print $rounded,"\n";
}
 
int() will always take the integer and drop the fraction.
int(3.9) = 3.0
int(-3.9) = -3.0
int(-3.9+0.5) = -3.0 *this is not proper rounding

ceil() always goes UP:
ceil(3.1) = 3.0
ceil(-3.1) = -3.0

floor() always goes DOWN:
floor(3.9) = 3.0
floor(-3.9) = -4.0

So I propose this logic:

foreach (@array){
if ($_ < 0) {
$rounded = int($_-.5);
} else {
$rounded = int($_+.5);
}
print $rounded,&quot;\n&quot;;
}


 
Ooops! Correction:

ceil() always goes UP:
ceil(3.1) = 4.0
ceil(-3.1) = -3.0
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top