I have an array of floats where data are stored with varying decimal points so some are 123.40000
, 123.45000
, 123.45600
...now if i want to print these values in the string without the 0s in the end in printf()
so that they are 123.4
, 123.45
, 123.456
, without those 0s in the end. Is this possible? If so, how?
4 Answers
Use the %g formatter:
printf( "%g", 123.4000 );
prints
123.4
Trailing zeros are removed, but unfortunately so is the trailing decimal point if the fractional part is zero. I don't know if there is actually any way of doing what you want directly using printf() - I think something like this is probably your best bet:
#include <stdio.h>
#include <math.h>
void print( FILE * f, double d ) {
if ( d - floor(d) == 0.0 ) {
fprintf( f, "%g.", d );
}
else {
fprintf( f, "%g", d );
}
}
int main() {
print( stdout, 12.0 );
print( stdout, 12.300 );
}
-
1Isn't it a bad idea to compare doubles? "if (d-floor(d) == 0.0)"? – himself Jan 15 '13 at 07:14
-
1@himself No, it's fine when you know what you are doing. “Never compare floating-point numbers for `==`” is just an approximation for the unsophisticated. – Pascal Cuoq Jun 16 '14 at 19:23
I don't know how hacky this is but:
float f = 124.000;
if (f == (int) f) {
printf("%.1f\n", f); /* .1 can be changed */
} else {
printf("%g\n", f);
}
Returns 124.0
.
float f = 124.123000;
if (f == (int) f) {
printf("%.1f\n", f); /* .1 can be changed */
} else {
printf("%g\n", f);
}
Returns 124.123
.

- 28,134
- 6
- 57
- 76
Use %g --
Print a double in either normal or exponential notation, whichever is more appropriate for its magnitude. 'g' uses lower-case letters, 'G' uses upper-case letters. This type differs slightly from fixed-point notation in that insignificant zeroes to the right of the decimal point are not included. Also, the decimal point is not included on whole numbers.

- 3,862
- 6
- 47
- 72
-
just a small query, what if i want to remove the trailing zeros but want to keep the decimal in whole numbers, like 124.00000 is 123. – sfactor Dec 07 '09 at 23:45
Print to a (large enough) buffer. Print the buffer ... and if the there's no '.'
in the buffer print a dot.
char buf[100];
sprintf(buf, "%g", val);
printf("%s", buf);
if (strchr(buf, '.') == NULL) putchar('.');
edit
The Standard specifies the #
flag:
# The result is converted to an ``alternative form''. [...] For a, A, e, E, f, F, g, and G conversions, the result of converting a floating-point number always contains a decimal-point character, even if no digits follow it. [...] For g and G conversions, trailing zeros are not removed from the result. [...]
... but you get the trailing zeros :(

- 106,608
- 13
- 126
- 198