0

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
venilla
  • 61
  • 1
  • 9

1 Answers1

0

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • First Thanks for your answer. Oh ok... so what i'm able to undertand is that strtod() gives me the right value but i'm not printing it correctly, right? – venilla Feb 19 '16 at 17:15
  • @kuttyV that's pretty much it. – Sourav Ghosh Feb 19 '16 at 17:16
  • @kuttyV `strtod()` probably won't give _exactly_ the right value, because most systems use binary floating point, not decimal, but it will be as close as possible. – Ian Abbott Feb 19 '16 at 18:01
  • @IanAbbott : Oh,so what do you think i can use instead of strtod() ? – venilla Feb 20 '16 at 14:44
  • @kuttyV It's not `strtod` that's the problem. It's a fundamental inability to represent most decimal fractions _exactly_ as a binary fraction with a finite number of digits. That's the same problem as not being able to represent 1/3 exactly as a decimal fraction with a finite number of digits. – Ian Abbott Feb 22 '16 at 12:50