3

We want to ensure that upto 10 decimal point values are kept while converting a double value to a string.

When we tried %e or %f, it will not keep more than 5 decimal points. When we tried %.14f, the small values (less than 1.0e-20) are not properly converted to string.

What format string to be used to keep upto 10 decimal points for double values?

Maanu
  • 5,093
  • 11
  • 59
  • 82

3 Answers3

6

Try %.17g to print with the most appropriate format for the double in question.

printf("%.17g\n", 10000.);
printf("%.17g\n", 240.0008);
printf("%.17g\n", 0.0000000013);

10000
240.0008
1.3000000000000001e-009
JasonD
  • 16,464
  • 2
  • 29
  • 44
2

I hope you do know that the float type (single-precision floating point) only ever keeps six decimal digits of precision? No conversion specifier can give precision that isn't there to begin with... (The double type keeps about 15 digits of precision, FYI.)

Link: http://en.wikipedia.org/wiki/Floating_point#Internal_representation

Update: JasonD has the answer to your updated question. Keeping this up for posteriority.

DevSolar
  • 67,862
  • 21
  • 134
  • 209
1

Float can store this number of decimal only if the number is small, otherwise use double.

In this example %.17g and %.14f are working without problem :

#include <stdio.h>

int main(void)
{
        double v = 0.12345678912345;
        printf("%.17g   %.14f  \n", v, v);
        return 0;
}

Displayed result :

0.12345678912345   0.12345678912345

From the documentation

f : Decimal floating point, lowercase 392.65

e : Scientific notation (mantissa/exponent), lowercase 3.9265e+2

g : Use the shortest representation: %e or %f 392.65

So using %.14f it is fine

Edit:

the small values (less than 1.0e-20) are not properly converted to string.

To display more than 20 decimal, you should use long double... But if you only need to store 1.0e-20 and do not need to print more than 6 decimal, float can hold it.

For long double, you need to use something like %.21Lg. For example :

#include <stdio.h>

int main(void)
{
        long double v = 0.123456789123456789123456789;
        printf("%.21Lg   %.21Lf   \n", v, v);
        return 0;
}
Community
  • 1
  • 1
benjarobin
  • 4,410
  • 27
  • 21
  • No, you shouldn't need `long double` to hold / display 1.0e-20. Even a simple `float` can hold values as small as 1.0e-37 (`FLT_MIN`)... – DevSolar Dec 18 '12 at 14:21
  • Indeed, if the value is small a simple float can hold it... I am going to fix it – benjarobin Dec 18 '12 at 14:30