How to extract the first three digits after the decimal point in any calculation in Perl?

StackOverflow https://stackoverflow.com/questions/14029866

  •  12-12-2021
  •  | 
  •  

Question

For a simple division like 1/3, if I want to extract only the first three digits after the decimal point from the result of division, then how can it be done?

Was it helpful?

Solution

You can do it with spritnf:

my $rounded = sprintf("%.3f", 1/3);

This isn't this sprintf's purpose, but it does the job.

If you want just three digits after the dot, you can do it with math computations:

my $num = 1/3;
my $part;
$part = $1 if $num=~/^\d+\.(\d{3})/;
print "3 digits after dot: $part\n" if defined $part;

OTHER TIPS

Using sprintf and some pattern matching. Verbose.

my $str;
my $num = 1/3;
my $res = sprintf("%.3f\n",$num);
($str = $res) =~ s/^0\.//;
print "$str\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top