2

Is there a way to print doubles in c using fprint so that the precision of the print is the least possible (So for example that an integer is always printed without decimals?)

I know that you can do something like printf("%.0f",number); But I am wondering if there is a way to use the minimum precision that makes the print exact (whenever the number can be expressed finitely in base 10 of course).

  • 2
    What would you expect to be printed for result of `1.0/3.0` expression? – c-smile Apr 12 '15 at 01:05
  • 1
    True. 1/3.0 may have as its closest `double` some value like `0.3333333333333333148296162562473909929395` What do you expect then? – chux - Reinstate Monica Apr 12 '15 at 01:09
  • That's why I said only when it can be expressed finitely in base 10. –  Apr 12 '15 at 01:11
  • 1
    Printing with with `DBL_DECIMAL_DIG` significant digits is enough to distinguish all `double` from each other. So additional digits past that have limited value. Code could use `printf("%.*le", DBL_DECIMAL_DIG - 1, some_double)` and that is an upper bound to the question. – chux - Reinstate Monica Apr 12 '15 at 01:14
  • Possible duplicate of [Avoid trailing zeroes in printf()](http://stackoverflow.com/questions/277772/avoid-trailing-zeroes-in-printf) – Jason C May 11 '16 at 07:14

1 Answers1

2

All finite double, encoded in base 10 or base 2 (the usual), or base 16 can be exactly finitely printed in base 10. DBL_MIN may take 100+ of digits to do so, but it is not infinite. printf() need not perform to that level. So it ends up being custom code and of course that can "printing doubles without zeros"

Recommend sprintf(buffer, "%.*e", DBL_DECIMAL_DIG - 1, some_double) and post-process the buffer to remove least significant 0 as needed for a "close enough" answer to code's goal.

Ref

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256