consider having a set of numbers:
my @array = (
1.788139343e-007, 0.0547055073198, -0.703213036125,
-0.583665880391, -1.41198285298, +0.171879081676,
-0.58966025098, -86.0627173425, -0.84449797709,
3.49876623321e-005, 3.02660429162, -0.256948695361);
I would like to have the decimal point aligned at the n-th column of a total width of m (maybe n=6 and m=25)
If using %f
i get nicely aligned numbers, but the numbers that require an scientific notation are being destroyed.
usging %g
interprets the precision argument after the dot as an absolute precision that results in different decimals after the decimal point.
And since the most numbers are in the range (-10, 10) I do not want to take the scientific notation %e
Are there any flags or format attributes (or combination of) that I overlooked?
the expected outcome would be:
foreach my $f (@array){
printf("[%+25.12g]$/", $f);
}
[ +1.788139343e-007 ]
[ +0.0547055073198 ]
[ -0.703213036125 ]
[ -0.583665880391 ]
[ -1.41198285298 ]
[ +0.0171879081676 ]
[ -0.58966025098 ]
[ -86.0627173425 ]
[ -0.84449797709 ]
[ +3.49876623321e-005 ]
[ +3.02660429162 ]
[ -0.256948695361 ]
or even better
[ +1.7881393430000e-007 ]
[ +0.0547055073198 ]
[ -0.7032130361250 ]
[ -0.5836658803910 ]
[ -1.4119828529800 ]
[ +0.0171879081676 ]
[ -0.5896602509800 ]
[ -86.0627173425000 ]
[ -0.8444979770900 ]
[ +3.4987662332100e-005 ]
[ +3.0266042916200 ]
[ -0.2569486953610 ]
(the question is about Perl but s?printf
s format string is rather independent, so I also added C
tag)
The [*]printf
function allow you to:
So if you know how much characters are before the dot (d = sprintf(buf, "%.0f", ar[i]);
), you can align the dot using (printf("[%*s %g", 4-d, "", ar[i]);
).
Then same logic to align the closing bracket:
#include <stdio.h>
int main()
{
double ar[] = {
1.788139343e-007, 0.0547055073198, -0.703213036125,
-0.583665880391, -1.41198285298, 0.171879081676,
-0.58966025098, -86.0627173425, -0.84449797709,
3.49876623321e-005, 3.02660429162, -0.256948695361};
for (int i = 0; i < 12; ++i)
{
/* buffer to count how much character are before the dot*/
char buf[64];
/* how much before the dot? */
int d = sprintf(buf, "%+.0lf", ar[i]);
/* write float with aligned dot and store second padding */
int e = printf("[%*s %+.15lg", 4-d, "", ar[i]);
printf("%*s]\n", 25-e, "");
}
return 0;
}
Gives:
[ +1.788139343e-07 ]
[ +0.0547055073198 ]
[ -0.703213036125 ]
[ -0.583665880391 ]
[ -1.41198285298 ]
[ +0.171879081676 ]
[ -0.58966025098 ]
[ -86.0627173425 ]
[ -0.84449797709 ]
[ +3.49876623321e-05 ]
[ +3.02660429162 ]
[ -0.256948695361 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With