Search code examples
perlprintfdecimal-point

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

Solution

  • You can also use Math::Round to do this:

    $ perl -MMath::Round=nearest -e 'print nearest(.001, 0.1), "\n"'
    0.1
    $ perl -MMath::Round=nearest -e 'print nearest(.001, 0.11111), "\n"'
    0.111