Search code examples
cdoubleprintf

How to hide leading zero in printf


The following outputs 0.23. How do I get it to simply output .23?

printf( "%8.2f" , .23 );

Solution

  • 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.