Maanu
Maanu

Reputation: 5203

Double 10 decimal Point Precision

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?

Upvotes: 3

Views: 5856

Answers (3)

benjarobin
benjarobin

Reputation: 4488

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;
}

Upvotes: 1

JasonD
JasonD

Reputation: 16582

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

Upvotes: 6

DevSolar
DevSolar

Reputation: 70243

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.

Upvotes: 2

Related Questions