@guy

A blog on technology and web culture

Guy Malachi


Source CodePerl Restrict Number Of Digits After Decimal Point

Here is Perl function that restricts the number of digits after the decimal point of a number.
To save it , paste it to a text file, and run it using Perl.
(or you can download it as a zip file)

#!/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);


The output of running this is:
The result for "11.299999999999",cut 3 digits is: 11.30
The result for "12.345",cut 3 digits is: 12.35
The result for "12.345",cut 2 digits is: 12.3
The result for "13.34",cut 3 digits is: 13.34
The result for "14.3",cut 3 digits is: 14.3
The result for "15",cut 3 digits is: 15

© 2011 Guy Malachi atguy.com, All Rights Reserved