Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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.

Thanks.

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

In reply to Math::round not rounding correctly by bulrush

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (5)
As of 2024-04-25 14:58 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found