Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have a variable, $distance. It is about 7 decimal places, and i want to have something like $roundeddistance = (distance rouneded to 2 decimal plaes).. is this possible??

thanks
Dipul

Replies are listed 'Best First'.
Re: Rounding Variables
by $code or die (Deacon) on Oct 09, 2000 at 20:36 UTC
    Actually if you do that, then you it will not round properly. e.g. it fails in the following examples:

    $distance=1.0050000     returns $roundeddistance = 1 (should be 1.01)
    $distance=1.9000000     returns $roundeddistance = 1.9 (should be 1.90)


    You should use sprintf function to round decimals:

    $roundeddistance = sprintf "%0.2f", $distance;
    Or, if you want it to to look a bit cleaner (i.e. have a leading '0' - 0.21 instead of .21) then you can use the following:

    $roundeddistance = sprintf "%1.2f", $distance;

    Hope this helps.
      Just to keep things straight, to get "0.21" you'd need to use
      $roundeddistance = sprintf "%4.2f", $distance;

      as the number to the left of the decimal in the format must be the minimum number of characters in the output including the leading zero (if indeed it's a zero) and the decimal.

      I should also add that rounding is not quite as simple as it first appears, depending on your field of work. For example, some need to always round 0.5 up, but others alternately round up and down in order to reduce the accumulated overestimate error in a sum of such rounded numbers. I've been tripped up by this a number of times...

Re: Rounding Variables
by kilinrax (Deacon) on Oct 09, 2000 at 20:09 UTC
    Try this:
    $roundeddistance = int($distance*100)/100;
    (assuming you want it rounded down, and not padded with zeroes. If not, see $code or die's suggestion below)
      Perfect.. thanks for the lightning fast help
      -Dipul