How to hide leading zero in printf

The C standard says that for the f and F floating point format specifiers:

If a decimal-point character appears, at least one digit appears before it.

I think that if you don't want a zero to appear before the decimal point, you'll probably have to do something like use snprintf() to format the number into a string, and remove the 0 if the formatted string starts with "0." (and similarly for "-0."). Then pass that formatted string to our real output. Or something like that.


double f = 0.23;

assert(f < 0.995 && f >= 0);  
printf(".%02u\n" , (unsigned)((f + 0.005) * 100));

Just convert it to an integer with the required accuracy

double value = .12345678901; // input
int accuracy = 1000; // 3 digit after dot
printf(".%03d\n", (int)(value * accuracy) );

Output:

.123

example source on pastebin


It is not possible to do it only using printf. The documention for printf says:

f  - "double" argument is output in conventional form, i.e.
     [-]mmmm.nnnnnn
     The default number of digits after the decimal point is six,
     but this can be changed with a precision field. If a decimal point
     appears, at least one digit appears before it. The "double" value is
     rounded to the correct number of decimal places.

Note the If a decimal point appears, at least one digit appears before it.

Therefore it seems you have to handcode your own formatter.

Tags:

Double

C

Printf