On Aug 21, Bryan Harris said:
Is this the best way to do simple integer round-ups? E.g. 3.2 -> 4?
I've been using:
$nines = 1 - 1/1e10;
$value = 3.2;
$roundedvalue = int($value + $nines);
... but it looks like $roundedvalue = $value + (-$value % 1) might be
better???
That technique I showed is only for integers. The generic function for
rounding *any* number to a multiple of 1, 10, 100, (or .1, .01, .001,
etc.) is as follows:
sub round {
my ($n, $places) = @_;
my $factor = 10 ** ($places || 0);
return int(($n * $factor) + ($n < 0 ? -1 : 1) * 0.5) / $factor;
}
To round a number to the nearest integer, use round($x). To round it to
the nearest 10, use round($x, 1). Nearest 100 is round($x, 2) and so on.
You can also round to the nearest tenth, hundredth, etc., by using a
negative second argument: round(5.28, -1) == 5.3.
If you always want to round a number up to the next integer value (unless
the value is an integer), use ceil() from the POSIX module. ceil(1.1) ==
2, ceil(1.9) == 2, ceil(2) == 2. To always round down, use floor() from
POSIX.
--
Jeff "japhy" Pinyan % How can we ever be the sold short or
RPI Acacia Brother #734 % the cheated, we who for every service
http://japhy.perlmonk.org/ % have long ago been overpaid?
http://www.perlmonks.org/ % -- Meister Eckhart
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>