C++20 std::format
This great new C++ library feature has the advantage of not affecting the state of std::cout
as std::setprecision
does:
#include <format>
#include <string>
int main() {
std::cout << std::format("{:.2} {:.3}\n", 3.1415, 3.1415);
}
Expected output:
3.14 3.145
The as mentioned at https://stackoverflow.com/a/65329803/895245 not if you don't pass the precision explicitly it prints the shortest decimal representation with a round-trip guarantee. TODO understand in more detail how it compares to: dbl::max_digits10
as shown at https://stackoverflow.com/a/554134/895245 with {:.{}}
:
#include <format>
#include <limits>
#include <string>
int main() {
std::cout << std::format("{:.{}}\n",
3.1415926535897932384626433, dbl::max_digits10);
}
See also: