I've always gone for:
use POSIX; sub round { floor($_[0] + 0.5) }
I've always wondered why Perl doesn't include a round function, it is something that tends to stump beginners. I also wondered if this was faster than japhy's code.
Benchmark: timing 100000 iterations of round1, round2... round1: 65 wallclock secs (64.59 usr + 0.00 sys = 64.59 CPU) @ 15 +48.23/s (n=100000) round2: 47 wallclock secs (47.78 usr + 0.00 sys = 47.78 CPU) @ 20 +92.93/s (n=100000)
And it seems to be slightly faster. I think it would also be marginally more understandable from a maintanace standpoint.

Also remember that if you work with floating point numbers you might get things you don't expect, for example, adding 0.01 to 0 99 times gives you 0.990000000000001.

The module Math::FixedPrecision seems promising, but unfortunatly it rounds 0.50 to 0 rather than 1.

use Math::FixedPrecision; for (my $i = Math::FixedPrecision->new(0); $i <= 1; $i += 0.01) { print $i, "\t", Math::FixedPrecision->new($i + 0.01, 0), "\n"; }
I know I've gone off on a slight tangent here.. but is there some nicer way to deal with this. I haven't used Math::Currency but that does look promising.

gav^


In reply to Re: Preferred Methods by gav^
in thread Preferred Methods by vek

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.