How do I pad a printf to take account of negative signs and variable length numbers?

后端 未结 2 1213
予麋鹿
予麋鹿 2021-02-02 08:09

I\'m trying to output some numbers in a log file and I want to pad a load of floats via the printf function to produce:

 058.0
 020.0
 038.0
-050.0
         


        
相关标签:
2条回答
  • 2021-02-02 08:43

    follows Erik, but I find

    printf("% 6.1f\n", myVar);
    

    also works.

    0 讨论(0)
  • 2021-02-02 08:46

    The width specifier is the complete width:

    printf("%05.1f\n", myVar);  // Total width 5, pad with 0, one digit after .
    

    To get your expected format:

    printf("% 06.1f\n", myVar);
    
    0 讨论(0)
提交回复
热议问题