简体   繁体   中英

Floating point formatting in printf()

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?

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 );
}

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM