Here's a straightforward solution based on something I used to do on my Commodore 64. :)

sub roundoff { my $num = shift; my $roundto = shift || 1; return int($num/$roundto+0.5)*$roundto; } foreach my $i (0.6, 1.2, 38.4, 88.6, 92.5) { printf "%5.1f ",$i; foreach my $j (1, 10, 100) { printf "%2d ", roundoff($i,$j); } print "\n"; }

Update: This actually rounds to the nearest number; I misread the OP's question. Here's a similar solution that always rounds up:

use POSIX qw(ceil); sub roundup { my $num = shift; my $roundto = shift || 1; return int(ceil($num/$roundto))*$roundto; }

Another Update: This function will find the right scale according to my understanding of the OPs question. You can use something like roundup($i,rightscale($j)) to get the auto-scaling behavior.

sub max { return $_[0] > $_[1] ? $_[0] : $_[1]; } sub rightscale { my $num = shift; return 10 ** max(int(log(abs($num))/log(10))-1,1); }

In reply to Re: Rounding up nearest ten, hundred etc by sgifford
in thread Rounding up nearest ten, hundred etc by nite_man

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.