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
  •  | 
  •  

質問

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?

役に立ちましたか?

解決

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;

他のヒント

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";
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top