in reply to Deleting trailing 0's after using sprintf
However, the behavior where 'g' suppresses trailing floating-point zeros seems to not be documented in the POD, which leads me to believe it's a compiler-dependant behavior (dependant on the compiler on which Perl was built) rather than clearly defined Perl behavior.
Of course someone else also already suggested a my $val = +sprintf "%.3f", $string; solution, which also will suppress trailing zeros. That also seemed pretty neat, as it relies on the fact that the + operator forces string-to-number coersion, which causes trailing zeros to be forgotten. ...a great solution.
However, if it turns out that 'g' suppressing trailing fp zeros is undefined (and possibly unreliable) behavior, and if for some reason you choose not to take advantage of Perl's ability to coerce strings into numeric values easily, the following solution may have merit instead.
use strict; use warnings; use Math::Round; my $test_value = 100.510; $test_value = fp_round( $test_value, 3 ); print "$test_value\n"; sub fp_round { my ( $val, $places ) = @_; return round( $val * ( 10 ** $places ) ) / ( 10 ** $places ); }
...Just another way to do it, I suppose.
All the OP is really trying to do is just round to a specific number of floating point places. Math::Round will round to the nearest integer. But that's easy to improve upon with a little math, as demonstrated in my snippet.
Dave
|
|---|