Re: Rounding up to the next .5



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
.



Relevant Pages

  • Rounding up to the next .5
    ... Not strictly a perl problem, I'm just happen to be using perl to do ... The courier charges by the half kilo and they never round down. ... next half kilo (unless the weight is an exact or .5 kilo already). ...
    (comp.lang.perl.misc)
  • Re: XQ and ->Qpi bug on large X
    ... you shouldn't be rounding to only two digits ... I am trying to make a similar point here about rounding; ... and round it, ... prior to using the input values in calculations. ...
    (comp.sys.hp48)
  • Re: My Completed RATECRYPT() function included below
    ... I was interested because most rounding functions do not round in an unbiased manner. ... I have seen various reports of clipper rounding problems but there are many different rounding methods and clipper chose a common one. ... The gaussian method (an unbiased estimator) gives the same answer you would get using a standard c compiler and printed with printf. ...
    (comp.lang.clipper)
  • Re: XQ and ->Qpi bug on large X
    ... plot of all specific values resembling a "normal distribution" ... we should round each value ... which fails if we start computing "mean square" ... the moment we begin rounding data, we make the data less reliable ...
    (comp.sys.hp48)
  • Re: Mike W. Corner
    ... tender and will round up in half-a-heartbeat, you can spin them out. ... Rounding up is one of your two primary defenses against a broach. ... Having a plan sure helps. ...
    (rec.motorcycles.dirt)