6

I want to print doubles in decimal notation with full precision (but without extra zeros at the end of the number). In C++ I can use:

std::setprecision(20);
cout << d; // Here d is a double

What would be the equivalent C code using printf?

StephQ
  • 2,032
  • 3
  • 19
  • 27
  • Possibly interesting: https://randomascii.wordpress.com/2012/03/08/float-precisionfrom-zero-to-100-digits-2/ – Martin Ba Dec 13 '16 at 10:13

3 Answers3

14

You can use the "%.20g" specifier. g is IMHO usually better than f since it doesn't print trailing zeros, and handles large/small values sensibly (changing to e format).

Also note that with the "g" specifier, the precision (the "20" in this case) specifies the number of significant digits rather than the number of digits after the decimal point.

janneb
  • 36,249
  • 2
  • 81
  • 97
8

Format is typically: %[flags][width][.precision][length]specifier, so for example, %.20f

If you pass in .* rather than .20, you can pass in an arbitrary precision at run time before the decimal value.

NOTE: you can use g too, however you should note that in some cases, there will be a difference in the result (between f and g - due to the way that the precision is interpreted.)

The main question though is what do you need that kind of precision for? (double/floats are imprecise)...

Nim
  • 33,299
  • 2
  • 62
  • 101
  • The question specifically states "but without extra zeros at the end of the number". This solution will add trailing zeros to the string printed. – qbert220 Sep 13 '11 at 11:53
  • As long as you have space to store the whole number, just use `snprintf` and then strip the trailing zeros yourself... – R.. GitHub STOP HELPING ICE Sep 13 '11 at 12:01
  • @qbert220, I did say "for example", and I was talking primarily about precision, but I will ammend... – Nim Sep 13 '11 at 12:04
  • @qbert: "extra" zeroes is a rather meaningless terms. Extra compared to what? A reasonable interpretation is zeroes that do not correspond to bits in the memory representation of `double` – MSalters Sep 13 '11 at 13:57
  • @MSalters - from the context of the question I understood it to mean trailing zeros. That is the behaviour of the c++ code the OP posted. – qbert220 Sep 13 '11 at 14:06
  • Sorry for the confusion raised by the question. What I ment there was avoid trailing zeros, and the %.20g format is perfect for this. – StephQ Sep 13 '11 at 15:02
  • 1
    @KRao: PS. Consider than 17 significant digits is enough to recover the original value for IEEE 754 double binary->decimal->binary conversion, so "%.20g" will print some unnecessary characters, "%.17g" is enough. – janneb Sep 13 '11 at 15:17
4

Use:

printf("%.20f", d);

That should work.

Taken from an online doc, the more general format is:

%[flags][width][.precision][length]specifier 

Go through the link to read about each token in the format.

Nawaz
  • 353,942
  • 115
  • 666
  • 851