Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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 be the equivalent C code using printf?

like image 618
StephQ Avatar asked Sep 13 '11 11:09

StephQ


People also ask

What is Setprecision 20 C++?

The C++ setprecision function is used to format floating-point values. This is an inbuilt function and can be used by importing the iomanip library in a program.

What is std :: Setprecision?

c++ - std::setprecision sets the number of significant figures.

What is the equivalent of print in C++?

The cout object is the only print method specifically created for C++. cout is an object of the ofstream type. C++ was designed around object-oriented programming and has completely different syntax compared to the functions deriving from C. Accordingly, cout is considered the standard way of printing strings in C++.


1 Answers

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.

like image 192
janneb Avatar answered Sep 19 '22 22:09

janneb