0

I want to keep all precision of double number. I try to use this to keep it in text file.

printf("%g", double_value);

And I want to convert it to double

double_value = atof(string_read_from_file);

I found it lost precision when I use printf, what's the correct method?

Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
Daniel YC Lin
  • 15,050
  • 18
  • 63
  • 96
  • 1
    The question this has been marked as a duplicate of has mediocre quality or rambling answers. A simple answer is you can use `printf("%.*g", DBL_DECIMAL_DIG, double_value);`. The `.*` in `%.*g` says to use the next argument as the number of digits to print. `DBL_DECIMAL_DIG` is the number of decimal digits needed to guarantee the printed string has enough digits to reproduce any original `double` value when converted back to `double`. It is defined in `floatl.h`. – Eric Postpischil Feb 09 '18 at 15:29
  • BTW, when using C99 (or newer) one can use `"%a"` to always print perfectly round-trip-able, albeit not-so-human-friendly, representation. – Greg A. Woods Feb 15 '18 at 00:46

0 Answers0