round numbers with a caveat?

L

Lance Hoffmeyer

Hey all,

I want to round numbers with one decimal place.
I know one can round in this manner:

sub round {
my($value) = shift;
return int($value + .5);
}


What I now need to add to this if that if a number is exactly
??.5 and is an even number then round down (i.e. 22.5 = 22)
and if a number is odd and ??.5 then round up (i.e. 21.5 = 22).

How can I test whether a number is even or odd?

sub round {
if ($value = "??.5 and even){ $value = $value - .1};
if ($value = "??.5 and odd"){ $value = $value + .1};

my($value) = shift;
return int($value + .5);
}
 
W

watsonbladd

Hey all,

I want to round numbers with one decimal place.
I know one can round in this manner:

sub round {
my($value) = shift;
return int($value + .5);

}

What I now need to add to this if that if a number is exactly
??.5 and is an even number then round down (i.e. 22.5 = 22)
and if a number is odd and ??.5 then round up (i.e. 21.5 = 22).

How can I test whether a number is even or odd?

sub round {
if ($value = "??.5 and even){ $value = $value - .1};
if ($value = "??.5 and odd"){ $value = $value + .1};

my($value) = shift;
return int($value + .5);

}

$int%2 is 0 for even, 1 for odd.
 
A

anno4000

Lance Hoffmeyer said:
Hey all,

I want to round numbers with one decimal place.
I know one can round in this manner:

sub round {
my($value) = shift;
return int($value + .5);
}

That works for positive values, but not for negative ones.
The normal way to round numbers in Perl is sprintf:

sprintf '%.0f', $value;

rounds to an integer. See also "perldoc -q round".
What I now need to add to this if that if a number is exactly
??.5 and is an even number then round down (i.e. 22.5 = 22)
and if a number is odd and ??.5 then round up (i.e. 21.5 = 22).

That is the standard and sprintf works this way.

for my $x ( -1.5, -0.5, 0.5, 1.5, 2.5, 3.5 ) {
my $y = sprintf'%.0f', $x;
print "$x -> $y\n";
}
How can I test whether a number is even or odd?

You don't have to for the purpose of rounding.

Besides taking the number mod 2, which has been suggested, you
can use the binary representation and test the least significant
bit:

my $parity = $y & 1 ? 'odd' : 'even';

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,044
Members
48,769
Latest member
Clifft

Latest Threads

Top