Perl – In Perl, how can I limit the number of places after the decimal point but have no trailing zeroes

decimal-pointperlprintf

This question is similar to "dropping trailing ‘.0’ from floats", but for Perl and with a maximum number of digits after the decimal.

I'm looking for a way to convert numbers to string format, dropping any redundant '0', including not just right after the decimal. And still with a maximum number of digital, e.g. 3

The input data is floats. Desired output:

0         -> 0
0.1       -> 0.1
0.11      -> 0.11
0.111     -> 0.111
0.1111111 -> 0.111

Best Answer

Use the following directly:

my $s = sprintf('%.3f', $f);
$s =~ s/\.?0*$//;

print $s

...or define a subroutine to do it more generically:

sub fstr {
  my ($value,$precision) = @_;
  $precision ||= 3;
  my $s = sprintf("%.${precision}f", $value);
  $s =~ s/\.?0*$//;
  $s
}

print fstr(0) . "\n";
print fstr(1) . "\n";
print fstr(1.1) . "\n";
print fstr(1.12) . "\n";
print fstr(1.123) . "\n";
print fstr(1.12345) . "\n";
print fstr(1.12345, 2) . "\n";
print fstr(1.12345, 10) . "\n";

Prints:

0
1
1.1
1.12
1.123
1.123
1.12
1.12345