flipper has asked for the wisdom of the Perl Monks concerning the following question:
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 itHowever, 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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: printf exact field width of floating point number
by BrowserUk (Patriarch) on Mar 28, 2012 at 09:35 UTC | |
by flipper (Beadle) on Mar 28, 2012 at 09:56 UTC | |
by aaron_baugher (Curate) on Mar 28, 2012 at 20:32 UTC | |
|
Re: printf exact field width of floating point number
by Marshall (Canon) on Mar 28, 2012 at 09:32 UTC | |
|
Re: printf exact field width of floating point number
by Anonymous Monk on Mar 28, 2012 at 16:42 UTC |