1

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
  • 1
    I need to show 0.123456 ..So can i use printf("%0*f",places,myfloatvalue);
    – Kiran k g
    Commented Sep 17, 2017 at 11:02
  • 1
    There is no (exact) float representation of 0.56 or 0.567. Commented Sep 17, 2017 at 11:47

2 Answers 2

6

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

printf("%g",myfloatvalue);
2
  • Almost, "%0g", would do it. Commented Sep 17, 2017 at 11:06
  • @DavidC.Rankin Disagree that a 0 is needed.
    – chux
    Commented Sep 17, 2017 at 15:00
3

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
5
  • 2
    How is "%0g" different from "%g"? There's no minimum width specified, so the number will never be padded. Commented Sep 17, 2017 at 12:03
  • It prints the leading zero in front of the decimal :) E.g man printf "0 The value should be zero padded. For d, i, o, u, x, X, a, A, e, E, f, F, g" Commented Sep 17, 2017 at 12:04
  • 1
    The C standard says it means: "leading zeros (following any indication of sign or base) are used to pad to the field width rather than performing space padding". Since the field width is unspecified and there's no padding it does nothing. You can test by trying printf("%g", 0.4); which I think you think will output .4 but will actually output 0.4. Commented Sep 17, 2017 at 12:40
  • Paul, don't get me wrong, I see what you are saying, and I agree with it. I also agree, that nowhere in man printf does in guarantee the printing of a leading zero. In fact in many cases, including the ., will not be printed absent a significant digit for that position. The only guaranteed way I can see to insure the zero is printed is with the %0g. It is in no way an error to include it. I get the padding argument, but I also note the lack of guarantee of the zero printing without it. Commented Sep 17, 2017 at 14:15
  • 1
    @DavidC.Rankin Adding 0 is not needed. "%g" for OP's numbers starts like "%f" and that is specified ( guaranteed) to "If a decimal-point character appears, at least one digit appears before it." so always a leading 0.
    – chux
    Commented Sep 17, 2017 at 14:59

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.