in reply to decimal precision

There are many ways to solve the problem, but here's a trick that may not leap straight to your finger tips:

use warnings; use strict; use bignum; my $e = 0.00141; my $o =1; for (1 .. 10){ "@{[$o *= $e]}" =~ /(0\.0*\d{0,5})/; print "$1\n"; }

Prints:

0.00141 0.0000019881 0.0000000028032 0.0000000000039525 0.0000000000000055730 0.0000000000000000078580 0.000000000000000000011079 0.000000000000000000000015622 0.000000000000000000000000022027 0.000000000000000000000000000031059

The @{[...]} trick is useful for interpolating the result of a chunk of code into a string. The rest should be pretty obvious, but note that if the regex doesn't match the print may generate some interesting results.

Update: bah, forgot about the rounding. Oh well, the interpolation trick is still worth knowing even if it doesn't really help solve the OP's problem.


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: decimal precision
by almut (Canon) on May 30, 2008 at 11:44 UTC
    The @{[...]} trick is useful for interpolating the result of a chunk of code into a string.

    No doubt a nice trick... but in this particular case, the conversion to string would happen implicitly, i.e. you could also do

    ($o *= $e) =~ /(0\.0*\d{0,5})/;

    Yet another way would be to use bignum's accuracy option (which also does take care of the rounding)

    use bignum accuracy => 5; my $e = 0.00141; my $o = 1; for (1 .. 10) { $o *= $e; print "$o\n"; } __END__ 0.0014100 0.0000019881 0.0000000028032 0.0000000000039525 0.0000000000000055730 0.0000000000000000078579 0.000000000000000000011080 0.000000000000000000000015623 0.000000000000000000000000022028 0.000000000000000000000000000031059

    (see Math::BigInt and Math::BigFloat for details on rounding modes, accuracy, precision, etc.)