开发者

Equivalent of C++ std::setprecision(20) using printf in C

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开发者_如何学JAVA be the equivalent C code using printf?


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.


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)...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜