views:

172

answers:

4

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

+5  A: 

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 );
}
anon
thanks a lot :)
sfactor
A: 

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.

Mick Walker
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
A: 

I don't know how hacky this is but:

http://codepad.org/e3Q3pUNd

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.

Nick Presta
A: 

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 :(

pmg