Reputation: 249
I would like to printf doubles such that the overall length is always the same and the number is rounded if too long.
For example, with overall length 7:
double a = 1.23456789;
double b = 12.3456789;
double c = 123.456789;
printf("a: %f\n", a);
printf("b: %f\n", b);
printf("c: %f\n", c);
would print:
a: 1.23457
b: 12.3457
c: 123.457
Is there a simple way to achieve this?
Upvotes: 2
Views: 929
Reputation: 3812
Yes, there is. See the specifications for printf
conversion specifiers. Use a #
to select the alternative form to keep the trailing zeros. Use the g
to obtain a representation with a fixed total number of digits. The .6
specifies the exact number of digits.
printf("a: %#.6g\n", a);
printf("b: %#.6g\n", b);
printf("c: %#.6g\n", c);
A precision of 6 digits happens to be the default, so this works as well
printf("a: %#g\n", a);
Upvotes: 2