Re: Rounding up to the next .5
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxx
- Date: 28 Apr 2007 22:47:45 GMT
Justin C <justin.news@xxxxxxxxxxxxxx> wrote in comp.lang.perl.misc:
Not strictly a perl problem, I'm just happen to be using perl to do
this.
I'm writing a utility for work that will calculate the price to send a
parcel. The courier charges by the half kilo and they never round down.
I'm trying to round weights (with up to two decimal places) up to the
next half kilo (unless the weight is an exact or .5 kilo already).
I've looked at the 'round' in the docs. You can round, for example, four
decimal places to three, two, one, or none, but there's no mention of
rounding, say, .3 to .5.
You can base one on the other. Rounding to the nearest half can be
seen as multiplying by two, then rounding to the nearest integer,
then dividing by two again. Generalizing, you get
sub round_to_multiple {
my ( $x, $factor) = @_;
$factor*sprintf '%.0f', $x/$factor;
}
which can be used as
for ( map 0.1*$_, 0 .. 10 ) {
printf "%s -> %s\n", $_, round_to_multiple( $_, 1/2);
}
Anno
.
- References:
- Rounding up to the next .5
- From: Justin C
- Rounding up to the next .5
- Prev by Date: Re: Problem with Image::Info
- Next by Date: Re: Rounding up to the next .5
- Previous by thread: Re: Rounding up to the next .5
- Next by thread: FAQ 4.53 How do I manipulate arrays of bits?
- Index(es):
Relevant Pages
|