Formatting float value in C language

2.4k views Asked by At

I need to print .5 as 0.5 using the printf statement in C language. It can be done easily using the following code.

printf("%03f", myfloatvalue);

But the situation is myfloatvalue is dynamic. So i am not sure whether it is a 3 character number, it could be .5 or .56 or .567. In the above cases i need to print as 0.5, 0.56, and 0.567.

2

There are 2 answers

5
David C. Rankin On BEST ANSWER

Continuing from my comment to Florian's answer, the format of "%0g" will print the shortest representation with the leading-zero, e.g.

#include <stdio.h>

int main (void) {

    float f[] = { .5, .56, .567 };
    size_t n = sizeof f/sizeof *f;

    for (size_t i = 0; i < n; i++)
        printf ("%0g\n", f[i]);

    return 0;
}

Example Use/Output

$ ./bin/floatfmt
0.5
0.56
0.567
2
Florian Zwoch On

%g does print the shortest possible representation of a float.

printf("%g",myfloatvalue);