Skip to content
alexandr-fonari edited this page Aug 11, 2012 · 1 revision

#Perl Snippets

Remarks: following code is not intended to be very efficient, rather somewhat understandable.

##Floating point precision

my ($f, $p) = (6.02 * 1.25, 2);

my $f1 = prec($f, $p);
print $f1;

use Math::BigFloat;

# float = prec(float full precision, desired precision);
sub prec(@_)
{
    my ($f, $p) = ($_[0], $_[1]);
    my $ret = Math::BigFloat->new($f);
    $ret->precision(-$p);

    return sprintf("%.${p}f", $ret); # rounding is done by BigFloat and NOT sprintf
}

Also see: http://stackoverflow.com/questions/1838808/how-do-i-set-the-floating-point-precision-in-perl

Clone this wiki locally