开发者

Simple C number formatting

This a very simple c question.

Is there a way to format a float for printf so that it has xx SIGNIFICANT decimals?

So I'm not talking about, say, %5.3f float, but if I had

float x=0.00001899383

How wou开发者_如何转开发ld I output 0.0000189 if I wanted up to the first three non-zero decimals?


"%.3g" will try to output three significant digits, either in scientific or fixed format.

at bjg:

The program

#include <stdio.h>

int main()
{
  double a = 123456789e-15;
  int i = 0;
  for( i=-10; i <= 10; ++i )
  {
    printf("%.3g\n", a );
    a *= 10;
  }
  return 0;
}

outputs

1.23e-07
1.23e-06
1.23e-05
0.000123
0.00123
0.0123
0.123
1.23
12.3
123
1.23e+03
1.23e+04
1.23e+05
1.23e+06
1.23e+07
1.23e+08
1.23e+09
1.23e+10
1.23e+11
1.23e+12
1.23e+13
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜