I'd like to print float
s via printf
as follows:
- (1) right-align into a string of given width (here
8
) - (2) show relevant decimal digits if possible, but no unneccesary trailing
0
s after.
- (3) also do this for rounded values, i.e. format
1.0
as"1."
With g
I cannot achieve (3), with f
I cannot achieve (2,3).
From the docs it seems that #
would do the trick for (3)
Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
So #g
can achieve (3), but it unfortunately does more than is written there: it also breaks the feature (2) by removing also relevant decimal digits (see below).
Here are some examples I tried, the last line shows what I am looking for:
number | 1.0 | -1.0 | 1.9 | -999.1 | 1.000001 |
---|---|---|---|---|---|
%8.2g |
1 |
-1 |
1.9 |
-1e+03 |
1 |
%8.g |
1 |
-1 |
2 |
-1e+03 |
1 |
%8g |
1 |
-1 |
1.9 |
-999.1 |
1 |
%#8.2g |
1.0 |
-1.0 |
1.9 |
-1.0e+03 |
1.0 |
%#8.g |
1. |
-1. |
2. |
-1.e+03 |
1. |
%#8g |
1.00000 |
-1.00000 |
1.90000 |
-999.100 |
1.00000 |
%8.2f |
1.00 |
-1.00 |
1.90 |
-999.10 |
1.00 |
%8.f |
1 |
-1 |
2 |
-999 |
1 |
%8f |
1.000000 |
-1.000000 |
1.900000 |
-999.099976 |
1.000001 |
%#8.2f |
1.00 |
-1.00 |
1.90 |
-999.10 |
1.00 |
%#8.f |
1. |
-1. |
2. |
-999. |
1. |
%#8f |
1.000000 |
-1.000000 |
1.900000 |
-999.099976 |
1.000001 |
???? |
1. |
-1. |
1.9 |
-999.1 |
1.000001 |
Can somebody help how to achieve the wanted output in the last line?