#!/usr/bin/perl
# restrict the number of digits after the decimal point
sub restrict_num_decimal_digits
{
my $num=shift;#the number to work on
my $digs_to_cut=shift;# the number of digits after
# the decimal point to cut
#(eg: $digs_to_cut=3 will leave
# two digits after the decimal point)
if ($num=~/\d+\.(\d){$digs_to_cut,}/)
{
# there are $digs_to_cut or
# more digits after the decimal point
$num=sprintf("%.".($digs_to_cut-1)."f", $num);
}
return $num;
}
my $a_number="11.299999999999";
#cut the third digit after the decimal point
print "\nThe result for \"$a_number\",cut 3 digits is: ";
print &restrict_num_decimal_digits($a_number,3);
$a_number="12.345";
#first cut the third digit after the decimal point
#then cut the second
print "\nThe result for \"$a_number\",cut 3 digits is: ";
print &restrict_num_decimal_digits($a_number,3);
print "\nThe result for \"$a_number\",cut 2 digits is: ";
print &restrict_num_decimal_digits($a_number,2);
$a_number="13.34";
# cut the third digit after the decimal point
print "\nThe result for \"$a_number\",cut 3 digits is: ";
print &restrict_num_decimal_digits($a_number,3);
$a_number="14.3";
# cut the third digit after the decimal point
print "\nThe result for \"$a_number\",cut 3 digits is: ";
print &restrict_num_decimal_digits($a_number,3);
$a_number="15";
# cut the third digit after the decimal point
print "\nThe result for \"$a_number\",cut 3 digits is: ";
print &restrict_num_decimal_digits($a_number,3);