In C++, setprecision(n) sets how many digits a stream prints for floating-point numbers. What n counts depends on the format: all significant digits by default, or digits after the point when fixed or scientific is on.
The setting stays on the stream until you change it. The default value is 6. Include <iomanip> to use it.
This is a manipulator with an argument. You write it inside a stream chain, like std::cout << setprecision(...), and it changes how the stream treats the data. It lives in <iomanip>, so remember to include that header.
Syntax
Put std::setprecision(n) into the stream. Add std::fixed for digits after the decimal point.
In each round of the loop, setprecision(p) sets a new number of significant digits.
With one digit, the number is 3. With two, 3.1. Every extra digit adds one more place.
The last digit is rounded, not cut. With four digits, 3.14159 becomes 3.142.
Frequently Asked Questions
It sets the number of digits printed for floating-point numbers. The default is 6.
Use cout << fixed << setprecision(2) << value. Without fixed, the 2 would count all digits.
Without fixed, the precision counts significant digits. If the number does not fit, the stream switches to scientific form. Add std::fixed to avoid it.
No. It only changes how the number is printed.
Yes. Add #include <iomanip>. You can also call cout.precision(n) without it.