Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 602
Brian Carlton Avatar asked Feb 20 '09 21:02

Brian Carlton


People also ask

How do I limit decimal places in Perl?

The f format lets you specify a particular number of decimal places to round its argument to. Perl looks at the following digit, rounds up if it is 5 or greater, and rounds down otherwise. Three functions that may be useful if you want to round a floating-point value to an integral value are int , ceil , and floor .

How do you limit the numbers after a decimal point?

Using Math.round() method is another method to limit the decimal places in Java. If we want to round a number to 1 decimal place, then we multiply and divide the input number by 10.0 in the round() method. Similarly, for 2 decimal places, we can use 100.0, for 3 decimal places, we can use 1000.0, and so on.

How do I restrict a float value to only two places after the decimal point in JavaScript?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.


1 Answers

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
like image 171
vladr Avatar answered Oct 30 '22 14:10

vladr