BarMeister has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to round off a number at a set amount of significant digits and was using the Math::BigFloat module to accomplish this. My problem is that I am trying to use the round_mode of 'common', which is in the documentation but is says that it is not a valid round_mode. For example: I am converting 0.006185625 to 6 significant digits...after using the 'common' round_mode it should go to 0.00618563. Anyone have any ideas on how to get the common round_mode to work?

Replies are listed 'Best First'.
Re: Math::BigFloat Rounding
by Joost (Canon) on May 23, 2007 at 00:29 UTC
    As far as the current docs are concerned, there is no "common" mode:

    All rounding functions take as a second parameter a rounding mode from one of the following: 'even', 'odd', '+inf', '-inf', 'zero' or 'trunc'

    I would guess you'd want to use 'odd' or '+inf'.

    Also note that always rounding "up" at .X5 (i.e. common rounding, or '+inf' for positive numbers) can cause statistical errors, so using 'odd' or 'even' is probably better, with the default of 'even' having the advantage of being the (or a) standard.

    See http://en.wikipedia.org/wiki/Rounding

    update: the wiki page also claims that using round-to-even (instead of round-to-odd) helps when the final result tends to near 0. That seems to make sense to me.

      When I looked at the docs I was actually looking at the BigInt docs which does have a common method which gives the same error though...BigFloat uses BigInt's round_method method. I am not going for any statistical relevance with this rounding...I am just trying to emulate the way in which MySQL rounds its float data types. Basically if it is >= 5 round up, < 5 round down.
Re: Math::BigFloat Rounding
by GrandFather (Saint) on May 23, 2007 at 00:30 UTC

    See the comments following the fround member descriptions in the Math::BigFloat docs.

    use Math::BigFloat; my $num = Math::BigFloat->new (0.006185625); print "Before: $num\n"; $num->fround (6, 'odd'); print "After: $num\n";

    Prints:

    Before: 0.006185625 After: 0.00618563

    DWIM is Perl's answer to Gödel