convert char * to double,without losing precision in c

1.2k views Asked by At

I need some help. I have to convert and STORE a char * into a double or long double without losing precision.

Indeed, i tried to use strtold and atof methods (also strtold), but these methods are rounding the value.

For example:

char * key  ="39.7519707";

double ld =strtod((char*)key,NULL);

printf("%lf", ld);

prints : 39.751971

but printf("%6.7f",ld) gives me the right value but I couldn't store into a variable.

1

There are 1 answers

5
Sourav Ghosh On BEST ANSWER

First of all, you only need %f format specifier to print a double.

Then, you're not losing precision by making use of strtod(), the output representation is the problem with how you use printf() with %f format specifier.

As per C11, chapter ยง7.21.6.1, fprintf()

[...] If the precision is missing, it is taken as 6;[...]

Next, when you did

printf("%6.7f",ld);

the precision became 7 and it outputs the value you expect to see.