Avoid trailing zeroes in printf()

前端 未结 14 2179
猫巷女王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:54

    Here is my first try at an answer:

    void
    xprintfloat(char *format, float f)
    {
      char s[50];
      char *p;
    
      sprintf(s, format, f);
      for(p=s; *p; ++p)
        if('.' == *p) {
          while(*++p);
          while('0'==*--p) *p = '\0';
        }
      printf("%s", s);
    }
    

    Known bugs: Possible buffer overflow depending on format. If "." is present for other reason than %f wrong result might happen.

    0 讨论(0)
  • 2020-11-22 07:57

    I would say you should use printf("%.8g",value);

    If you use "%.6g" you will not get desired output for some numbers like.32.230210 it should print 32.23021 but it prints 32.2302

    0 讨论(0)
提交回复
热议问题