|We don't bite newbies here... much|
Math::round not rounding correctlyby bulrush (Scribe)
|on Dec 23, 2014 at 19:26 UTC||Need Help??|
bulrush has asked for the
wisdom of the Perl Monks concerning the following question:
Perl 5.8.8 on Redhat Linux
I'm doing "use Math::Round qw(:all)" and later in my program doing "$l=round($x)" where $x is 3461.5. $l ends up being 3461 when it should be 3462. How can I ensure Math::Round is being used?
I have not used Math::Round before. And there is no "round" in my utils include file or anywhere else, otherwise I'd get an error at some time.
p.s. I have tried using several rounding methods after doing some Googling and it looks like Math::Round would work best. I seem to have the most problems with numbers ending with .5.
EDIT: This gave me no error, but it also did not round correctly to 3462.
$x=$l1*$l2; $l=Math::Round::round($x);In my main program: The sprintf method doesn't round correctly in all cases, and neither does using POSIX ceil() and floor() in my main program. My test program works, but not my main perl program. So I was trying to ensure the Math::Round::round() function was being called.
EDIT 2: When the number is 3461.5 it should round to 3462 but rounds to 3461. How do I round this correctly? Try these test programs at the shell prompt. The first program rounds to 2 decimals. The second to 0 decimals to show the rounding problem. This is the actual calculation I'm having trouble with.
perl -e 'print sprintf("%.4f",(3010*1.15))."\n"' # Outputs 3461.5000 perl -e 'print sprintf("%.2f",(3010*1.15))."\n"' # Outputs 3461.50 perl -e 'print sprintf("%.0f",(3010*1.15))."\n"' # Outputs 3461