David Homes
David Homes

Reputation: 2796

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 would I output 0.0000189 if I wanted up to the first three non-zero decimals?

Upvotes: 2

Views: 469

Answers (1)

Peter G.
Peter G.

Reputation: 15114

"%.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

Upvotes: 10

Related Questions