After reading the posts I realize the original post wasn't about just rounding up to the next multiple of ten but I thought it was interesting anyway so here is my answer. I thought it was neat but I had to fix it up to deal with negative numbers.
#!/usr/bin/perl -w
use strict;
sub round_up_tens($) {
my $n = int shift;
if(($n % 10) == 0) {
return($n);
} else {
my $sign = 1;
if($n < 0) { $sign = 0; }
$n = int ($n / 10);
$n *= 10;
if($sign) {
$n += 10;
}
return($n);
}
return(-1);
}
print "-24 => " . round_up_tens(-24) . "\n";
print "-14 => " . round_up_tens(-14) . "\n";
print "-10 => " . round_up_tens(-10) . "\n";
print "-4 => " . round_up_tens(-4) . "\n";
print "0 => " . round_up_tens(0) . "\n";
print "4 => " . round_up_tens(4) . "\n";
print "7 => " . round_up_tens(7) . "\n";
print "10 => " . round_up_tens(10) . "\n";
print "14 => " . round_up_tens(14) . "\n";
print "144 => " . round_up_tens(144) . "\n";
Prints:
-24 => -20
-14 => -10
-10 => -10
-4 => 0
0 => 0
4 => 10
7 => 10
10 => 10
14 => 20
144 => 150
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|