I'm trying to print floating point numbers 1.2345678, 0.1234567, 123.45678 using printf in such a way that only the first n characters are printed. I want these number to line up. The %g format specifier in printf("%*g", n, var) does this but the specifier is not treating the 0 in 0.1234567 as a significant figure. This causes the alignment of 0.1234567 to go off wrt to the other two figures.
What's the best way to align the numbers in the formats given. Either by treating 0 as significant with %g or using some other method?
By definition leading zeros are not significant figures. If you want the first N digits to be printed, including leading zeros, convert first the numbers to strings and use
printf("%.*s", n, var_as_string)
.This way, the first
n
characters are indeed printed, as you asked. Of course the decimal mark.
, as any other character, is now significant, contrary to%g
.No, it doesn't - with
%*g
you're only specifying a minimum field width… In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result. [fromman 3 printf
]But perhaps you meant
%.*g
, specifying the precision …, the maximum number of significant digits, which behaves according to your problem description.What's the best way depends on the value range of the numbers. If we have just positive numbers similar to those you posted, we could simply reduce the precision by one for a leading zero, e. g.:
A brute force method tries various precisions of
%.*g
until success.The major obstacle to calculating the width of the print out before calling
printf()
is that corner cases exist like 0.9995. The subtle effects of rounding make it that it is simpler to callsprintf()
a subsequent time. Additional code could be uses to make a better initial guess rather than starting atprec = n - 1
Output