Hi monks,

I have a floating point number, and a certain number of characters to print it in. I want the number to use all of the available area (padded with spaces), and display the maximum precision that will fit.

From perldoc -f sprintf, it sounds like  %.${WIDTH}g is on the right tracks, though the decimal point may not be included in the calculation:

You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a . followed by a number

...

For "g" and "G", this specifies the maximum number of digits to show, including thoe prior to the decimal point and those after it

However, when I use %.6g, I get output up to 8 characters long. Brute force script:

for $format (qw{ %.6g %6.6g %6g %.6f %6.6f %6f}){ print "\n$format\n"; for (12344.99, 1.12345678, 0.000000123, 0.12345678, 123.45678, + 123456, 12345.678901){ $str = sprintf "$format",$_; print length($str)." - '$str'\n"; } }

output

%.6g 5 - '12345' 7 - '1.12346' 8 - '1.23e-07' 8 - '0.123457' 7 - '123.457' 6 - '123456' 7 - '12345.7' %6.6g 6 - ' 12345' 7 - '1.12346' 8 - '1.23e-07' 8 - '0.123457' 7 - '123.457' 6 - '123456' 7 - '12345.7' %6g 6 - ' 12345' 7 - '1.12346' 8 - '1.23e-07' 8 - '0.123457' 7 - '123.457' 6 - '123456' 7 - '12345.7' %.6f 12 - '12344.990000' 8 - '1.123457' 8 - '0.000000' 8 - '0.123457' 10 - '123.456780' 13 - '123456.000000' 12 - '12345.678901' %6.6f 12 - '12344.990000' 8 - '1.123457' 8 - '0.000000' 8 - '0.123457' 10 - '123.456780' 13 - '123456.000000' 12 - '12345.678901' %6f 12 - '12344.990000' 8 - '1.123457' 8 - '0.000000' 8 - '0.123457' 10 - '123.456780' 13 - '123456.000000' 12 - '12345.678901'

Thanks!


In reply to printf exact field width of floating point number by flipper

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.