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?
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