Rob Dixon wrote:
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

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.


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;
}

sub round_to_places {
    my ( $n, $places ) = @_;
    return sprintf '%.*f', $places, $n;
    }



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to