Jaap has asked for the wisdom of the Perl Monks concerning the following question:

if i use my $var = sprintf "%1.2f", (-1 * 0.0000002); then $var == '-0.00'; But what i really want is that var then becomes just '0'. I can write a sub to do this but can i not tell sprintf somehow to remove trailing zeros? (apart from the minus)

Replies are listed 'Best First'.
Re: sprintf on floating point
by Jaap (Curate) on Sep 05, 2002 at 14:22 UTC
    I found it. If you numerically add zero to the sprintf result, it works:
    my $var = sprintf "%1.2f", '0.001'; print "\$var = " . ($var + 0) . "\n";
Re: sprintf on floating point
by fruiture (Curate) on Sep 05, 2002 at 14:12 UTC
    <wrong>$_ = sprintf('%.f',sprintf('%1.2f', 2e-7))</wrong>

    How about that?

    UPDATE: sorry, i didn't test this. The '0+' approach is much better.

    --
    http://fruiture.de
      perl -e 'print sprintf "%f", sprintf "%0.2f", 0.1' 0
      However, you could do it this way (though without using sprintf):
      perl -e 'print 0 + sprintf "%0.2f", 0.001' 0 perl -e 'print 0 + sprintf "%0.2f", 0.1234' 0.12
      Does that help?

      -- Dan

        It does help however the first one doesn't work.
      There's one tiny little problem with this: 0.12345 becomes 0 too. That should become 0.12