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

I want what "%g" does for intermediate-sized numbers. So:
DB<19> printf("%g",3.00); 3 DB<20> printf("%g",3.001); 3.001
I do want variable-length output (so %f is out), but I don't ever want exponential notation. I have heard that "%_f" does this in C. Why not perl???? Dearest Monk, enlighten me please!

Replies are listed 'Best First'.
Re: printing floats nicely
by ww (Archbishop) on Sep 22, 2010 at 02:41 UTC

    See perldoc -f sprintf; that's correct; the sprintf doc covers printf formatting options in some detail, including (just 'for example'),

    precision, or maximum width You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a "." followed by a number. For floating point formats, with the exception of 'g' and 'G', this specifies the number of decimal places to show (the default being 6), e.g.: # these examples are subject to system-specific variation printf '<%f>', 1; # prints "<1.000000>" printf '<%.1f>', 1; # prints "<1.0>" printf '<%.0f>', 1; # prints "<1>" printf '<%e>', 10; # prints "<1.000000e+01>" printf '<%.1e>', 10; # prints "<1.0e+01>" For 'g' and 'G', this specifies the maximum number of digits to show, including prior to the decimal point as well as after it...

    and
    For floating point conversions ("e f g E F G"), numbers are usually assumed to be the default floating point size on your platform (double or long double), but you can force 'long double' with "q", "L", or "ll" if your platform supports them
Re: printing floats nicely
by ikegami (Patriarch) on Sep 21, 2010 at 22:20 UTC

    I have heard that "%_f" does this in C.

    No, that's not C.

    I do want variable-length output

    s/\.?0+\z// if /\./;
Re: printing floats nicely
by Anonymous Monk on Sep 21, 2010 at 22:07 UTC
    $x =~ s/^(.*[.].*[^0]|.*[.])0*$/$1/; $x =~ s/\.$//;