Avoid trailing zeroes in printf()

前端 未结 14 2184
猫巷女王i
猫巷女王i 2020-11-22 07:18

I keep stumbling on the format specifiers for the printf() family of functions. What I want is to be able to print a double (or float) with a maximum given number of digits

14条回答
  •  不思量自难忘°
    2020-11-22 07:42

    What about something like this (might have rounding errors and negative-value issues that need debugging, left as an exercise for the reader):

    printf("%.0d%.4g\n", (int)f/10, f-((int)f-(int)f%10));
    

    It's slightly programmatic but at least it doesn't make you do any string manipulation.

提交回复
热议问题