Gossamer Forum
Home : General : Perl Programming :

rounding the figures

Quote Reply
rounding the figures
Rounding the figures:

$line = 630;
$line = $line - ($line % 65);
$lines = $line/65;

The above given simply divides 630 by 65 and give the result for 9.692 in rounded figures i.e. 9 only.

---------

I also used the sprintf function to get the result in rounded figures like...

$line = 630;
$line = $line - ($line % 65);
$lines = $line/65;

$rounded = sprintf("%.2f", $lines);

print "$rounded\n";

-------------

Both of these are working fine, but as you see if the result is greater than 9.5, it should be rounded to 10 and if its less than 9.5 (as per rules of mathematics) it should be rounded to 9 and this piece of code even round 9.99 to 9? Is there any way to round the figures e.g. to 10 when its greater than 9.5

Any help?

TIA,

Zeshan.



Quote Reply
Re: [zeshan] rounding the figures In reply to
Code:
my $rounded = int($line + .5);

Or to work with negative numbers also:

Code:
my $rounded = int($line + .5 * ($line <=> 0));

Last edited by:

Paul: Apr 29, 2003, 2:34 PM
Quote Reply
Re: [Paul] rounding the figures In reply to
Its not working.....Try it below. 630/65 = 9.69, it should be rounded to 10, but no its rounded to 9 again.

$line = 630;
$line = $line - ($line % 65);
$lines = $line/65;

$rounded = int($lines + .5);

print "$rounded";

Last edited by:

zeshan: Apr 29, 2003, 2:42 PM
Quote Reply
Re: [zeshan] rounding the figures In reply to
Works for me.

paul> perl -e "print int(9.69 + .5);"
paul> 10
Quote Reply
Re: [Paul] rounding the figures In reply to
In Reply To:
Works for me.

paul> perl -e "print int(9.69 + .5);"
paul> 10


Sorry Paul, I forgot to remove this line from the code, when I removed it from the code, now its working fine.

$line = $line - ($line % 65);

Once again thanks for your help.