0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
prashant
  • 97
  • 1
  • 1
  • 8

2 Answers2

2

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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Galimov Albert
  • 7,269
  • 1
  • 24
  • 50
0

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";
Galimov Albert
  • 7,269
  • 1
  • 24
  • 50
fbynite
  • 2,651
  • 1
  • 21
  • 25
  • Note `s/^0\.//` regex can fail when you have **setlocale** to some locales, such as Russian. – Galimov Albert Dec 25 '12 at 11:10
  • @PSIAlt, I thought locales only mattered under `use locale;`. Are you sure? – ikegami Dec 25 '12 at 11:17
  • @ikegami yes `perl -MPOSIX -e 'setlocale(LC_ALL, "ru_RU.UTF8");printf "%.3f", 1/3;'` prints `0,333` for me. – Galimov Albert Dec 25 '12 at 11:24
  • @PSIAlt, Since a single period matches a single character. Does that not get rid of the locale issue? Is there another reason to avoid using a single period in the regex? By single period, I mean not escaping the period. – fbynite Dec 25 '12 at 12:08
  • @fbynite oh, i got the idea. I think its "too-unstrict", but should work too – Galimov Albert Dec 25 '12 at 13:33