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
Use the following directly:
...or define a subroutine to do it more generically:
Prints:
You can use
sprintf
combined witheval
.For example:
outputs:
You can also use Math::Round to do this:
This will give you the output your looking for: