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
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.