I have two double number a
and b
double a = 1.01, b = 1.2345678
then printf("%.4f %.4f", a, b)
will output
1.0100 1.2345
but I want to output
1.01 1.2345
that is, remove the useless 0s.
I have two double number a
and b
double a = 1.01, b = 1.2345678
then printf("%.4f %.4f", a, b)
will output
1.0100 1.2345
but I want to output
1.01 1.2345
that is, remove the useless 0s.
%.4f
will always prints up to 4 decimal by padding zeros.
You can remove %.4f
and use %g
for printing exact value with out padding zeros
g,G The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.
Not excactly what you want but you could use %g
instead of %f
like below:
double a = 1.01, b = 1.2345678;
printf("%.4g %.4g\n", a, b);
The precision value is interpreted differently in "g" format than in "f" format. The precision for "f" specifies the number of digits after the decimal point. The precision for "g" specifies the maximum number of significant digits printed.
If you specify a width ... then you're going to get that width.
Simply use "%g" or "%f" instead.
From the "man" page:
http://linux.die.net/man/3/printf
g, G
The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.