c++ how to get “one digit exponent” with printf

后端 未结 5 2150
说谎
说谎 2020-12-06 05:48

Is there a way to print in scientific notation less than 3 places for exponent part of number? The 6.1 formatting doesn\'t affect exponent but only the number part:

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 06:07

    C/C++ specifies at least two exponent digits with printf("%e",...). To print only 1, and to deal with Visual Studio which, by default, prints at least 3, additional code is needed.

    Consider IOStreams @Dietmar Kühl

    If C++ code still wants to use printf() style formats:

    Adjusting the value of a double before calling printf() too often results in rounding issues, range shorting and general corner case failures like dealing with log10(0.0). Also consider large double just near a power-of-10 where log10() may come up short, -0.0, INF, NAN.

    In this case, better to post-process the string.

      double var = 1.23e-9;
      //                    - 1 . x e - EEEEE \0
      #define ExpectedSize (1+1+1+1+1+1+  5 + 1)
      char buf[ExpectedSize + 10];
      snprintf(buf, sizeof buf, "%.1e", var);
      char *e = strchr(buf, 'e');  // lucky 'e' not in "Infinity" nor "NaN"
      if (e) {
        e++;
        int expo = atoi(e);
        snprintf(e, sizeof buf - (e - buf), "%1d", expo);
      }
      printf("'%6s'\n", buf);  // '1.2e-9'
    

    Note: %e is amiable to post-processing as its width is not so unwieldy as "%f". sprintf(buf, "%f", DBL_MAX) could be 1000s of char.

提交回复
热议问题