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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |