I'm a little confused. Okay, I know that int does not round a number, it just lops off everything after the decimal. So, after reading some other posts here, I go with sprintf. Specifically, I need an integer and I want to correctly lop everything off after the decimal. Here's my formula:

$rounded=sprintf("%.0f",$unrounded); This works for most cases, but I'm getting some funny output from my script when the decimal is .5. Here is the verbose output from my script where it performs a calculation, tells me the unrounded number, and then tells me what the rounded number is:

(script output)
SO the equation to figure out sub trait A1 looks like this
7 + (2 - (0.5 * 9)) and comes up as 4.5
that is rounded to 4
SO the equation to figure out sub trait A2 looks like this
7 + (2 - (0.5 * 9)) and comes up as 4.5
that is rounded to 4
SO the equation to figure out sub trait A3 looks like this
7 + (5 - (0.5 * 9)) and comes up as 7.5
that is rounded to 8

So, my question is, why did it round DOWN for two cases, and round UP for one case?


-oakbox


In reply to Rounding With sprintf anomaly? by oakbox

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.