Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: Rounding values upwards on an arbitrary basis

by xdg (Monsignor)
on Jul 02, 2003 at 21:09 UTC ( [id://270962]=note: print w/replies, xml ) Need Help??


in reply to Rounding values upwards on an arbitrary basis

Here's an approach to the rounding up function. I've left the algorithm of what to round by at each level as exercise for the reader, as you said you know how using log()

CODE: #!/usr/bin/perl -w use strict; # $n is number to round, $d is "divisor" for rounding units sub roundup { my ($n, $d) = @_; return ( int( $n / $d ) + ( ( $n % $d ) ? 1 : 0 ) ) * $d; } for my $i ( 0,4,5,6,9,10,11,24,25,26) { print "$i -> " . roundup($i,5) . "\n"; } for my $i ( 99,100,101,124,125,126,149,150,151) { print "$i -> " . roundup($i,25) . "\n"; } for my $i ( 999, 1000, 1001, 1249, 1250, 1251, 1499,1500,1501) { print "$i -> " . roundup($i,250) . "\n"; } RESULT: 0 -> 0 4 -> 5 5 -> 5 6 -> 10 9 -> 10 10 -> 10 11 -> 15 24 -> 25 25 -> 25 26 -> 30 99 -> 100 100 -> 100 101 -> 125 124 -> 125 125 -> 125 126 -> 150 149 -> 150 150 -> 150 151 -> 175 999 -> 1000 1000 -> 1000 1001 -> 1250 1249 -> 1250 1250 -> 1250 1251 -> 1500 1499 -> 1500 1500 -> 1500 1501 -> 1750

-xdg

Addendum: This rounds up, but not over -- for the case where 4 rounds up to 5, but 5 rounds up to 10 (!), then the function is even simpler:

sub roundup { my ($n, $d) = @_; return ( int( $n / $d ) + 1 ) * $d; }

Code posted by xdg on PerlMonks is public domain. It has no warranties, express or implied. Posted code may not have been tested. Use at your own risk.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://270962]
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found