views:

72

answers:

1

Hi guys, 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 take about, say, %5.3 float, but if I had

float x=0.00001899383

how would i output 0.0000189 if i wanted UP TO the first three non-zero decimals?

thanks! I'm not stating at home this weekend so I don't have my C book around

+9  A: 

"%.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
Peter G.
But that wouldn't deal with the non-zero part of the question. This will just the format first 3 digits regardless
bjg
@bjg, no, it prints 3 **significant** digits, but will use exponential notation if there are more than a couple leading zeros..
R..
@R.. My bad. I stand corrected.
bjg
+1 For solution + good demo
Jamie Wong
Peter, thanks! I'm actually just doing a couple c functions within an Obj-C app and had forgotten this stuff for a long time.like Jamie said, +1 + +1
dhomes