For some reason I was under the impression that the int function was doing rounding rather than truncating, so took a quick look at perldoc -f int, which mentioned that you should use POSIX::floor() rather than int. And sure enough, the code snippet above provides what I'd consider to be incorrect results for negative values. The OP doesn't mention if the input values will ever be negative, but consider the following:

#!/usr/bin/perl use strict; use warnings; use POSIX; my $num = -1.2; my $rounded_pos = (POSIX::floor($num*2))/2; my $rounded_int = (int $num*2)/2; printf "Rounded is %.1f for %f using POSIX\n", $rounded_pos, $num; printf "Rounded is %.1f for %f using int\n", $rounded_int, $num; __END__ Output: Rounded is -1.5 for -1.200000 using POSIX Rounded is -1.0 for -1.200000 using int

Simple change, and seems to be more robust. (Added: Although I may just be misinterpreting "rounding down" -- I think "down" is "in the negative direction" as opposed to "closer to zero". Hmm.)


In reply to Re^2: Round down to '.5' or '.0' by Nkuvu
in thread Round down to '.5' or '.0' by awohld

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.