Expanding on bobf's solution, I wrote a module a while ago that uses POSIX::ceil(), floor() and pow() functions that allows me to round to a specified number of decimal places including negative values to round to the nearest 10, 100 etc. Here's the module
# Rounders.pm
#
# ========
package Rounders;
# ========
use strict;
use warnings;
use Exporter;
our @ISA = qw{Exporter};
our @EXPORT = qw{rndZero rndPlaces};
use POSIX qw(ceil floor pow);
# -------
sub rndZero
# -------
{
my $val = shift;
my $rounded = $val < 0 ?
POSIX::ceil($val - 0.5) : POSIX::floor($val + 0.5);
return $rounded;
}
# ---------
sub rndPlaces
# ---------
{
my($val, $places) = @_;
my $rounded =
rndZero($val * POSIX::pow(10.0, $places)) /
POSIX::pow(10.0, $places);
return $rounded;
}
1;
a test script to demonstrate usage
#!/usr/local/bin/perl
#
use strict;
use warnings;
use Rounders;
my $val = 724934.817084;
print qq{Original value - $val\n};
print
q{Rounded to whole number - },
rndZero($val),
qq{\n},
qq{Rounded to decimal places\n};
printf qq{ %2d - %s\n},
$_, rndPlaces($val, $_)
for -4 .. 4;
and the results
Original value - 724934.817084
Rounded to whole number - 724935
Rounded to decimal places
-4 - 720000
-3 - 725000
-2 - 724900
-1 - 724930
0 - 724935
1 - 724934.8
2 - 724934.82
3 - 724934.817
4 - 724934.8171
I hope this is of use. Cheers, JohnGG |