CKTIS / C++
std::setprecision — numeric formatting precision
std::setprecision from <iomanip> sets a stream's precision. With std::defaultfloat, a positive precision sets the maximum number of significant digits. With std::fixed and std::scientific, a nonnegative precision sets the number of digits after the decimal separator, while a negative precision gives the default of six. The setting remains active for subsequent operations.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <iomanip>
// std::setprecision(int n) returns an object of unspecified type.
out << std::setprecision(n);
in >> std::setprecision(n);std::setprecision(n) from <iomanip> creates a manipulator whose return type is unspecified by the standard. The expression out << std::setprecision(n) acts like out.precision(n) and supports further chaining with <<. It changes the stream's formatting state, not the stored numeric value.
The meaning of n depends on the mode. With std::defaultfloat, it is the maximum number of significant digits for positive n; output may use ordinary or exponential notation, and trailing zeros are normally omitted. For n >= 0, std::fixed writes n digits after the decimal separator, and std::scientific writes that many digits after the separator in the significand of exponential notation. The manipulator also accepts negative n and stores it in the stream. In both of these modes, formatting treats a negative precision as if it were omitted and uses the default of six digits after the decimal separator. With std::hexfloat, precision is ignored.
Formatting rounds the textual representation rather than simply truncating digits. Increasing precision does not improve the accuracy of the stored value. The manipulator neither sets the field width nor changes integer output formatting. The decimal separator depends on the stream's locale.
The setting remains active until changed. std::defaultfloat changes the mode but does not restore an earlier precision. In helper code, save and restore precision() and, if the mode changes, flags(). The syntax in >> std::setprecision(n) is valid and sets the input stream's precision state; it does not limit the number of digits consumed by ordinary floating-point extraction.
Examples
#include <iomanip>
#include <iostream>
#include <locale>
int main() {
std::cout.imbue(std::locale::classic());
const double value = 12.375;
const auto oldPrecision = std::cout.precision();
const auto oldFlags = std::cout.flags();
std::cout << std::defaultfloat << std::setprecision(4)
<< value << '\n';
std::cout << std::fixed << std::setprecision(2)
<< value << '\n';
std::cout << 1.5 << '\n';
std::cout << std::scientific << value << '\n';
std::cout.precision(oldPrecision);
std::cout.flags(oldFlags);
}
Result
12.38 12.38 1.50 1.24e+01
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.