user3504959
user3504959

Reputation: 69

How do you remove the 0 when using printf, .precision on float type

I have this line of code:

printf("%.3d%.2f\n", ones, value);

However, this doesn't work ,because the %.2f produces 0.25.

Is there a modifier I can add to make it just print .25, aka removing the 0?

Upvotes: 1

Views: 149

Answers (1)

paxdiablo
paxdiablo

Reputation: 881093

In C, no, there's not.

What you can do is print to a temporary buffer, then adjust what you print based on that:

char buff[30];
sprintf (buff, "%.2f", value);              // Get value to temp buffer
if ((buff[0] == '0') && (buff[1] == '.'))   // Starts with "0."?
    printf ("%s", buff+1);                  // Yes, skip the zero..
else
    printf ("%s", buff);                    // No, print the lot.

However, it looks like you always guarantee that the floating point is less than one, since you're running together the integer and floating point value in the output. If that's the case, you can possibly just use something like:

printf ("%6.2f", value + ones);

Upvotes: 1

Related Questions