Reputation: 97
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?
Upvotes: 0
Views: 1041
Reputation: 7357
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;
Upvotes: 2
Reputation: 2661
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";
Upvotes: 0