Yet another example of how to do rounding; this time using sprintf (I
think I grabbed this from a TechRepublic Perl Tip email)....
--------
ROUNDING NUMBERS USING SPRINTF
Perl doesn't have a function specifically for rounding numbers to a
specified number of decimal places. However, you can use the sprintf
function
for this purpose.
The following example shows a function to round numbers that is
implemented using the "%nf" format string in sprintf. The function accepts
a
value to be rounded and an optional number of digits after the decimal
place.
If the number of digits isn't specified, 2 is used as a default.
sub Round
{
my ($value, $places);
$value = shift || return 0;
$places = shift || 2;
return sprintf "%.${places}f", $value;
}
We could use this routine as follows:
$quantity = 3;
$price = 2.00;
$priceEach = $price / $quantity;
print "Price each: $priceEach\n";
print "Rounded: " . Round($priceEach) . "\n";
print "4 places: " . Round($priceEach, 4) . "\n";
Doing math that requires rounding is a challenge in Perl. This function
makes rounding a little less challenging.
---------------------
William
--
Lead Developer
Knowmad Services Inc. || Internet Applications & Database Integration
http://www.knowmad.com
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]