On 07/12/2010 04:07, Harry Putnam wrote:
Is there any way to reduce the amount of decimals math might be
carried too short of printf?
I always find printf to end up taking a fair bit of time, since I've
forgotten most of what I ever knew about it each time I run into a
need for it.
I just wondered if there is any other kind of limiting mechanism?
It would be handy if simple math like:
my $ans = (261 / 59.00)
could be made to show only 2 decimal places like:
4.42
instead of:
4.42372881355932
Hi Harry
The canonical idiom for rounding floating-point numbers is to use
sprintf. I don't really understand your problem with it, but you could
hand-roll a rounding function if that helps. Take a look at the program
below.
Rob
use strict;
use warnings;
sub round_to_places {
my ($n, $places) = @_;
my $factor = 1;
$factor *= 10 while $places--;
return int($n * $factor + 0.5) / $factor;
}
my $ans = 261 / 59;
print round_to_places($ans, 2), "\n";
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/