Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Printing floating point numbers with minimum significant figures 1

Status
Not open for further replies.

WebDrake

Programmer
Sep 29, 2005
106
PL
Hello all,

Suppose I wanted to print a floating point number (float or double) with 2 decimal places' precision. So, of course I would write,

printf("%.2f",x);

Now, suppose I want instead to print the number with the minimum number of decimal places required to print it accurately. So, if x==0.1 I want to print "0.1" but if x==1.1695 I want to print "1.1695", etc.

How do I do this?

Many thanks,

-- Joe
 
Perhaps [tt]%g[/tt]?
Code:
#include <stdio.h>

int main(void)
{
   double value[] = { 0.1, 1.1695, 10, 100.001, 0.123456789 };
   size_t i;
   for ( i = 0; i < sizeof value / sizeof *value; ++i )
   {
      printf("value[%lu] = [blue]%g[/blue]\n", (long unsigned)i, value[i]);
   }
   return 0;
}

/* my output
value[0] = 0.1
value[1] = 1.1695
value[2] = 10
value[3] = 100.001
value[4] = 0.123457
*/
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top